Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Finding smaller number of 2 numbers inputted by user

13

Comments

  • Registered Users, Registered Users 2 Posts: 6,236 ✭✭✭Idleater


    I'm guessing you would need two files? one for passwords and one for usernames?

    Have a look at CSV or json files. Or XML for that matter.

    When you are done storing and reading from the files, you can next look at a basic hash stored value instead of plain text. Then after that you can look at salt.


  • Registered Users, Registered Users 2 Posts: 6,236 ✭✭✭Idleater


    Idleater wrote: »
    Have a look at CSV or json files. Or XML for that matter.

    When you are done storing and reading from the files, you can next look at a basic hash stored value instead of plain text. Then after that you can look at salt.

    This can henceforth be called the Twitter secure password protection method.

    https://blog.twitter.com/official/en_us/topics/company/2018/keeping-your-account-secure.html


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Hope someone here can help me out, this program prints out employee details and asks the user to enter how many hours they've worked,Run into a bit trouble here, in the method gettotalpay its not returning the any answer but 0, any ideas? thanks.
    public class Employee {
    
    	private String name;
    	private int age;
    	private String employeeNumber;
    	private double amountPerHour;
    	private double hoursWorked;
    	private double totalWage;
    	private static final String MOTTO = "Work Hard Play Hard!";
    
        public Employee() {
    
        	this("x",0,"xx",0.0,0.0);
        }
    
        public Employee(String Name){
    
        	this(Name,0,"xx",0.0,0.0);
        }
    
        public Employee(String Name,int Age){
    
        	this(Name,Age,"xx",0.0,0.0);
    
        }
    
        public Employee(String Name,int Age,String EmployeeNumber){
    
        	this(Name,Age,EmployeeNumber,0.0,0.0);
        }
    
        //public Employee(String Name,int Age,String EmployeeNumber,double AmountPerHour){
    
       //	this(Name,Age,EmployeeNumber,Age,AmountPerHour,0.0);
       // }
    
        public Employee(String Name,int Age,String EmployeeNumber,double AmountPerHour,double HoursWorked){
    
        	this.name = Name;
        	this.age = Age;
        	this.employeeNumber = EmployeeNumber;
        	this.amountPerHour = AmountPerHour;
        	this.hoursWorked =HoursWorked;
    
        }
    
        public static String getMOTTO()
        {
          return Employee.MOTTO;
        }
    
        public void setName(String value)
        {
           this.name = value;
        }
    
        public String getName()
        {
        	return this.name;
        }
    
        public void setAge(int value)
        {
        	this.age = value;
        }
    
        public int getAge()
        {
        	return this.age;
        }
    
        public void setEmployeeNumber(String value)
        {
        	this.employeeNumber = value;
        }
    
        public String getEmployeeNumber()
        {
        	return this.employeeNumber;
        }
    
        public void setAmountPerHour(double APH)
        {
        	this.amountPerHour = APH;
        }
    
        public double getAmountPerHour()
        {
        	return this.amountPerHour;
        }
    
        public void setHoursWorked(double HS)
        {
         	this.hoursWorked = HS;
        }
    
        public double getHoursWorked()
        {
       	 return this.hoursWorked;
        }
    
        public double gettotalPay()
        {
        	Scanner sc = new Scanner(System.in);
    
        	System.out.println("Please enter the total hours your worked this week:");
        	double hoursWorked = sc.nextDouble();
    
        	double totalWage = this.amountPerHour * this.hoursWorked;
        	return totalWage;
        }
    
         public String toString()
         {
         	StringBuilder strB = new StringBuilder();
    
         	strB.append(" Name: ");
         	strB.append(this.getName() + "\n");
         	strB.append(" Age: ");
         	strB.append(this.getAge() + "\n");
         	strB.append(" EmployeeNumber: ");
         	strB.append(this.getEmployeeNumber() + "\n");
         	strB.append("Rate Per Hour: ");
         	strB.append(this.getAmountPerHour() + "\n");
         	strB.append(" Total Wage this week: ");
         	strB.append(this.gettotalPay() + "\n");
         	return strB.toString();
         }
    
    
    
    
    
    }
    

    new Employee_Tester().tester_Application();
    
    	}
    
    	public void tester_Application()
    	{
    		Employee s1 = new Employee();
    		s1.setName("John");
    		s1.setAge(32);
    		s1.setEmployeeNumber("112345");
    		s1.setAmountPerHour(8.75);
    		s1.setHoursWorked(0);
    
    	    System.out.println(s1.toString());
    
        	//Employee s2 = new Employee();
    
    		//Employee s3 = new Employee();
    
    		//Employee s4 = new Employee();
    
    		//Employee s5 = new Employee();
    
    		//Employee s6 = new Employee();
    
    		//Employee s7 = new Employee();
    


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Sorted, changed double hoursworked to this.hoursworked.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Can anyone tell me why this program doesn't break out of the loop when the user presses 0 to exit?
    import java.util.Scanner;
    
    
    public class PassWord {
    
    	private String userName;
    	private String passWord;
    	private String name[] = {"kevin","john"};
    	private String pass [] = {"cat","cow"};
    	private String answer = "";
    	private int sum;
    	private int num1;
    	private int num2;
    	private int num3;
    	private int choice;
    	private int i;
    
    
    
    
        public void passWordChecker()
        {
            Scanner sc = new Scanner(System.in);
            for(int i = 0;i<3;i++){
    
          	System.out.println("Please enter the correct name and password:");
          	System.out.println();
    
          	System.out.println("Please enter your Username: ");
            userName = sc.nextLine();
    
          	System.out.println("Please enter your password: ");
            passWord = sc.nextLine();
    
          	if(userName.equals(name[0]) && passWord.equals(pass[0]))
          	{
          		welcomeMessage();
          		menuOption();
          		menuSelection();
          	}
           else if(userName.equals(name[1])&& passWord.equals(pass[1]))
          	{
          		welcomeMessage();
          		menuOption();
          		menuSelection();
          	}
           }
    
           if(!userName.equals(name[0])&& !(passWord.equals(pass[0])))
          {
         	wrongPassWord();
          }
    
    
    
    
    
    
        }
    
        public void welcomeMessage()
        {
            System.out.println("************************");
    		System.out.println("************************");
    		System.out.println("*** WELCOME TO THE******");
    		System.out.println("**SECRET GAME MENU!!!!**");
    		System.out.println("************************");
    		System.out.println("************************");
        }
    
        public void menuOption()
        {
            System.out.println("Please select an option:");
    		System.out.println("1.) Addition");
    		System.out.println("2.) Subtraction");
    		System.out.println("3.) Division");
    		System.out.println("0.) Exit");
        }
    
        public void menuSelection()
        {
          do{
          	Scanner sc = new Scanner(System.in);
          	System.out.println("Please makea a Selection");
    
          	choice = sc.nextInt();
          	sc.nextLine();
    
          	switch(choice){
    
          		case 1: additionOption();
          		break;
    
          		case 2: subtractionOption();
          		break;
    
          		case 3: divisionOption();
          		break;
    
          		case 0: exitMessage();
          		break;
    
          		default:
          			System.out.println("INVALID SELECTION!!!!");
          	}
          }while(choice!=0);
        }
    
        public double additionOption()
        {
            Scanner sc = new Scanner(System.in);
    		System.out.println("Please enter a number: ");
    		num1 = sc.nextInt();
    
    		System.out.println("Please enter a second number: ");
    		num2 = sc.nextInt();
    
    		System.out.println("Please enter a third number: ");
    		num3 = sc.nextInt();
    
    		sum = num1 + num2 + num3;
    
    		System.out.println("The sum of three nums is: " +sum);
    
    		return sum;
        }
    
        public double subtractionOption()
        {
           return 0;
        }
    
        public double divisionOption()
        {
          return 0;
        }
    
        public void wrongPassWord()
        {
          System.out.println("Wrong PassWord");
    	  Scanner sc = new Scanner(System.in);
    	  System.out.println("Do you want another chance [Y]/[N]: ");
    	  answer = sc.nextLine();
    
    	  if(answer.equals("Y"))
    	  {
    	  	passWordChecker();
    	  }
    	  else if(answer.equals("N"))
    	  {
    	  	exitMessage();
    	  }
        }
    
        public void exitMessage()
        {
          System.out.println("Goodbye.");
        }
    

    public class PassWord_Tester{
    	public static void main(String[] args){
    
    		 PassWord password = new PassWord();
    
    		 password.passWordChecker();
    


  • Posts: 0 [Deleted User]


    I can see two loops that you might be referring to: one in the menuSelection() method and the other in the passWordChecker() method.

    From messing around with that code, it seems that menuSelection() is working okay, but once I pressed '0', it prompted me for username/password again. Is this additional prompt for username/password that was unexpected? In that case, it's because of the for loop in the passWordChecker() method; just take that out and if the user enters '0' in the menu selection, the program will cleanly exit.

    Once you take the for loop out though, you'll find that the wrongPassWord() method never gets called; check the logic in the 'if' for that.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    . Is this additional prompt for username/password that was unexpected? .

    That's the one ya, I have the for loop in there though because I want the user to have three chances to enter the correct information and if they fail that's when the wrong message method is called, anyway to keep the for loop in it and to get working properly?


  • Closed Accounts Posts: 1,758 ✭✭✭Pelvis


    Set i=3 in the if statements that call the menu selection.

    Also, in the wrongPassword method be sure to take into account case sensitivity.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Pelvis wrote: »
    Set i=3 in the if statements that call the menu selection.

    Also, in the wrongPassword method be sure to take into account case sensitivity.

    Thanks for the reply, its breaks the loop if you enter in kevin, cat and then press 0 but if you enter john,cow , the goodbye message method and wrong password method are both called.


  • Posts: 0 [Deleted User]


    I started making some small tweaks to the code, so that I could reply with a few hints. Problem then was I became invested and didn't want to write a partial solution, so I wrote more code. Bad habit... really bad habit. :o

    Hopefully I haven't taken too much of the "learning" out of it for you. All I can really say is have a look at the code (I've commented a couple of places) and see what you think!

    Anyway... basic gist of what I did:
    • Changed the formatting. (Well, my IDE this this for me - I'm far too lazy to change it back).
    • Copy/paste to/from boards code seemed to have mangled some of the println. I fixed where I spotted them, but might be worth to double check.
    • Made userName and passWord method ("local") variables instead of class variables. You could probably do the same for the other variables (sum, num, choice), up to yourself though really.
    • Made NAME[] and PASS[] static and uppercase (Java convention)
    • Made the username/password check into its own method (just a bit neater that way).
    • In the core method (passWordChecker()), I changed the for loop into a while loop. The while loop has a flag keepGoing, that we use to check when to come out of the loop.
    • Changed wrongPassWord() method to return a boolean indicating whether to continue or not. This is a "flow of control" thing. I bullsh1t on about that in later on.
    import java.util.Scanner;
    
    public class PassWord {
    
        private static final int MAX_LOGIN_ATTEMPTS = 3;
    
        private static final String NAME[] = {"kevin", "john"};
        private static final String PASS[] = {"cat", "cow"};
        private String answer = "";
        private int sum;
        private int num1;
        private int num2;
        private int num3;
        private int choice = 0;
    
        public void passWordChecker() {
    
            int nTries = 0;           // Keep track of how many unsuccessful login attempts have been made
            boolean keepGoing = true; // Flag to check should we stay in the main loop
    
            Scanner sc = new Scanner(System.in);
    
            while (keepGoing) {
                System.out.println("Please enter the correct name and password:");
                System.out.println();
    
                System.out.println("Please enter your Username: ");
                String userName = sc.nextLine();
    
                System.out.println("Please enter your password: ");
                String passWord = sc.nextLine();
    
                if (isValidLogin(userName, passWord)) {
                    welcomeMessage();
                    menuOption();
                    menuSelection();
                } else {
                    // If we get in here, then the user entered the wrong username / password.
                    nTries++;
    
                    if (nTries >= MAX_LOGIN_ATTEMPTS) {
                        // User has exhausted all login attempts. Set the 'keepGoing' flag to false, so that we break out
                        // of the while loop.
                        System.out.println("All login attempts failed.");
                        keepGoing = false;
                    } else {
                        // User still has some login attempts remaining. Ask if they want to continue.
                        keepGoing = wrongPassWord();
                    }
    
                }
            }
        }
    
        // Added this method because OCD
        private boolean isValidLogin(String userName, String passWord) {
            if (userName.equals(NAME[0]) && passWord.equals(PASS[0])
                || userName.equals(NAME[1]) && passWord.equals(PASS[1])) {
                return true;
            } else {
                return false;
            }
        }
    
        public void welcomeMessage() {
            System.out.println("************************");
            System.out.println("************************");
            System.out.println("*** WELCOME TO THE******");
            System.out.println("**SECRET MENU!!!!**");
            System.out.println("************************");
            System.out.println("************************");
        }
    
        public void menuOption() {
            System.out.println("Please select an option:");
            System.out.println("1 Addition");
            System.out.println("2 Subtraction");
            System.out.println("3 Division");
            System.out.println("0 Exit");
        }
    
        public void menuSelection() {
            do {
                Scanner sc = new Scanner(System.in);
                System.out.println("Pleasea a Selection");
    
                choice = sc.nextInt();
                sc.nextLine();
    
                switch (choice) {
    
                    case 1:
                        additionOption();
                        break;
    
                    case 2:
                        subtractionOption();
                        break;
    
                    case 3:
                        divisionOption();
                        break;
    
                    case 0:
                        exitMessage();
                        break;
    
                    default:
                        System.out.println("INVALID ACTION!!!!");
                }
            } while (choice != 0);
        }
    
        public double additionOption() {
            Scanner sc = new Scanner(System.in);
            System.out.println("Pleas enter a number: ");
            num1 = sc.nextInt();
    
            System.out.println("Pleas enter a second number: ");
            num2 = sc.nextInt();
    
            System.out.println("Pleas enter a third number: ");
            num3 = sc.nextInt();
    
            sum = num1 + num2 + num3;
    
            System.out.println("The sum of three nums is: " + sum);
    
            return sum;
        }
    
        public double subtractionOption() {
            return 0;
        }
    
        public double divisionOption() {
            return 0;
        }
    
        public boolean wrongPassWord() {
    
            Scanner sc = new Scanner(System.in);
    
            System.out.println("Wrong password ye langer.");
            System.out.println("Do you want another chance [Y]/[N]: ");
            answer = sc.nextLine();
    
            if (answer.equalsIgnoreCase("Y")) {
                return true;
            } else {
                return false;
            }
        }
    
        public void exitMessage() {
            System.out.println("Goodbye");
        }
    }
    

    "Flow Of Control" Bullsh1t Paragraph
    They way the code was written, the passwordChecker() method would call to the wrongPassWord() method. In turn the wrongPassWord() could call the passwordChecker() method. In Java, it puts these calls onto a "stack":
    passwordChecker()
    wrongPassWord()
    passwordChecker()
    wrongPassWord()
    passwordChecker()
    wrongPassWord()
    .....
    

    Each time Java has a method call from inside another method, it puts the method call on top of the stack. The problem is the stack can only grow so much before it has memory problems. It would have been pretty hard (and laborious) to get your code to that stage, but the possibility was there. For this I thought it was a neater solution to just have the wrongPassWord() method return a flag to the passwordChecker() method, and let passwordChecker() look after the "flow of control".


  • Advertisement
  • Posts: 0 [Deleted User]


    • Copy/paste to/from boards code seemed to have mangled some of the println. I fixed where I spotted them, but might be worth to double check.

    Yup, happened when I pasted too, so definitely check those println.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Yup, happened when I pasted too, so definitely check those println.

    Thanks so much that, helps a lot.


  • Registered Users, Registered Users 2 Posts: 6,262 ✭✭✭Buford T Justice


    If we're being OCD, you could shorten the isValidLogin method to
      // Added this method because OCD
      private boolean isValidLogin(String userName, String passWord) {
       return (userName.equals(NAME[0]) && passWord.equals(PASS[0]) || userName.equals(NAME[1]) && passWord.equals(PASS[1]));
      }
    


  • Posts: 0 [Deleted User]


    If we're being OCD, you could shorten the isValidLogin method to
      // Added this method because OCD
      private boolean isValidLogin(String userName, String passWord) {
       return (userName.equals(NAME[0]) && passWord.equals(PASS[0]) || userName.equals(NAME[1]) && passWord.equals(PASS[1]));
      }
    

    Yeah, absolutely right. But I didn't want to do too much, in case it lost transparency of what I had done. Likely be compiled away anyway.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Is calling methods from within methods considered bad practice in java?


  • Registered Users, Registered Users 2 Posts: 3,945 ✭✭✭Anima


    It's fine, all programs are is functions calling other functions. It's the fact that you had a function A calling function B with B calling into A again. That's a loop that could lead to a stack overflow if there was no terminating condition.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Could I also make scanner static? that way I wouldn't have to make a new instance of it in every method?


  • Registered Users, Registered Users 2 Posts: 3,945 ✭✭✭Anima


    You could or just it make a class member so you don't have to create it in every method.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Is this method overloading basically the same method but with different parameters?
    int sideA = 5;
    		int sideB = 5;
    		int sideC = 5;
    		int sideD = 5;
    		int sideE = 5;
    		int sideF = 5;
    		int sideG = 5;
    		int sideH = 5;
    		int sideI = 5;
    		int finalResult;
    
    		finalResult = getAnswer(sideA,sideB)+ getAnswer(sideC,sideD,sideE)+getAnswer(sideF,sideG,sideH,sideI);
    
    		System.out.println("The result is: " +finalResult);
    
    
    
    
    	}
    
    	public static int getAnswer (int a,int b)
    	{
    		return a*b+20;
    	}
    
    	public static int getAnswer(int c,int d,int e)
    	{
    		return c*d*e+10;
    	}
    
    	public static int getAnswer(int f,int g,int h,int i)
    	{
    		return f*g*h+10;
    	}
    


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 6,289 ✭✭✭Talisman


    Method Overloading is a fancy term for allowing you to reuse the same method name within a class.
    • The method name must be the same.
    • The arguments must be different.
    • The return type may be different.

    A subclass could inherit one version of a method from its parent class and then declare another overloaded version in its own class definition.

    Method Overriding is similar to Method Overloading however the primary rules are different:
    • The method name must be the same.
    • The arguments must be the same.
    • The return type must be the same or a covariant.

    In an interview situation they may try to trip you up by talking about Compile Time Polymorphism, Runtime Polymorphism and Dynamic Method Dispatch.

    Method Overloading is Compile Time Polymorphism - the method that is going to get called will be determined at compile time.

    Method Overriding is Runtime Polymorphism / Dynamic Method Dispatch - the method to be called is determined by the JVM at runtime.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Head is wrecked at the minute, how do I pass the answer of one method to another method to be calculated?
    Scanner sc = new Scanner(System.in);
    
    
    
    		System.out.println("Please enter num: ");
    		int a = sc.nextInt();
    
    		System.out.println("Please enter num2: ");
    		int b = sc.nextInt();
    
    		System.out.println("Answer is: "+ getNumber(a,b));
    
    		System.out.println("Please enter a num: ");
    		int c = sc.nextInt();
    
    		System.out.println("Please enter another num: ");
    		int d = sc.nextInt();
    
    		myResult = getSum(c,d);
    
    		System.out.println("Answer is: "+getSum(c,d)+myResult);
    
    
    
    
    
    	}
    
    	public static int getNumber(int a,int b)
    	{
    		return a*b;
    	}
    
    	public static int getSum(int c,int d)
    	{
    		return c*d;
    	}
    


  • Closed Accounts Posts: 1,758 ✭✭✭Pelvis


    What are you trying to achieve? Your two methods are performing the same task.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Pelvis wrote: »
    What are you trying to achieve? Your two methods are performing the same task.

    I want to pass the answer from the first method to the second so it can be calculated but I'm not sure how to do it.


  • Closed Accounts Posts: 1,758 ✭✭✭Pelvis


    Both methods return a single int but expect two arguments. So you can pass the answer from the first but what will be your second argument?
    getSum( getNumber(a,b) , ???)
    


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Pelvis wrote: »
    Both methods return a single int but expect two arguments. So you can pass the answer from the first but what will be your second argument?
    getSum( getNumber(a,b) , ???)
    

    I figured it out I think
    import java.util.Scanner;
    public class Practice2{
    	public static void main(String[] args){
    
    			Scanner sc = new Scanner(System.in);
    
    			System.out.println("Please enter a number: ");
    			int num1 = sc.nextInt();
    
    			System.out.println("Please enter a second number: ");
    			int num2 = sc.nextInt();
    
    			System.out.println("Answer is: " +getProduct(num1,num2));
    
    			int sum = getProduct(num1,num2);
    
    
    
    			System.out.println("Please enter another number: ");
    			int num3 = sc.nextInt();
    
    			System.out.println("and just One more: ");
    			int num4 = sc.nextInt();
    
    			int sum2 = getNum( num3, num4);
    
    			System.out.println("Answer is: "+sum * +sum2);
    
    
    
    	}
    
    	public static int getProduct(int num1,int num2)
    	{
    		return num1*num2;
    	}
    
    	public static int getNum(int num3,int num4)
    	{
    		return num3*num4;
    	}
    


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 98 ✭✭haskellgeek


    again your still using duplicating one method instead put a total_count outside your main, or in your main whichever you prefer and ditch the second method like this
    import java.util.Scanner;
    public class Practice2{
    	public static void main(String[] args){
    			Scanner sc = new Scanner(System.in);
    			System.out.println("Pleaser a number: ");
    			int num1 = sc.nextInt();
    			System.out.println("Pleaser a second number: ");
    			int num2 = sc.nextInt();
    			int sum = getProduct(num1,num2);
    			System.out.println("'Answer" + sum);
    			System.out.println("Pleaser another number: ");
    			int num3 = sc.nextInt();
    			System.out.println("and One more: ");
    			int num4 = sc.nextInt();
    			int sum2 = getProduct( num3, num4);
    			int total_count = getProduct(sum, sum2);
    			System.out.println("Answer " + total_count);
    			sc.close();
    	}
    
    	public static int getProduct(int num1,int num2){
    		return num1*num2;
    	}
    }
    


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Lets say you don't want the user to enter integer values, how would catch that?
    import java.util.Scanner;
    import java.util.InputMismatchException;
    public class Country{
    
    	public static void main(String[]args){
    
    
    		boolean isValid = true;
    		String Country1 = "Ireland";
    		String Country2 = "England";
    		String Country3 = "France";
    
    		countryOfOrigin(isValid,Country1,Country2,Country3);
    	}
    
    	public static void countryOfOrigin(boolean isValid,String Country1,String Country2,String Country3){
    
          Scanner sc = new Scanner(System.in);
          do{
             try{
    	  		System.out.println("Please enter your country of origins: ");
    	  	    String Country = sc.nextLine();
    	  	    int Country6 = Integer.parseInt(Country);
    
    	  	    if(Country.equals("Ireland") || Country.equals("England") || Country.equals("France")){
    	  	       System.out.println("Thank");
    	  	       isValid = true;
    	  	    }
    	  	    else{
    	  	    	System.out.println("Wrong,please enter another country again: ");
    	  	    	isValid = false;
    	  	    }
    	  	}
    	  	catch(InputMismatchException e)
    	  	{
    	  		System.out.println("Please enter strings only!");
    	  	}
    	  }while(!isValid);
    	}
    
    
    


  • Posts: 0 [Deleted User]


    Quick and durty, off the top of my head :
    try {
        Integer.parseInt(Country);
    } catch (NumberFormatException nfe) {
        System.out.println("Hey assbutt, " + Country + " is not an 'int'");
    }
    

    JavaDoc References:
    However, a better idea would be to validate the input String (generally considered bad practice to use Exceptions to control program flow):
    if ( /* Your code here */ ) {
        System.out.println("Hey assbutt, " + Country + " is not an 'int'");
    }
    

    JavaDoc References:


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Is there anyway to get view the code of a .exe file?


  • Registered Users, Registered Users 2 Posts: 6,236 ✭✭✭Idleater


    Is there anyway to get view the code of a .exe file?

    Look up decompiler or debugger


  • Advertisement
  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Idleater wrote: »
    Look up decompiler or debugger

    Looks complicated enough, I'll leave it for now I think.


  • Registered Users, Registered Users 2 Posts: 6,236 ✭✭✭Idleater


    Looks complicated enough, I'll leave it for now I think.

    Indeed, c decompiling is an art in itself. I wouldn't have the faintest idea where to start, but knew someone who was very good at it.

    What is it that you would like to understand from that program? Perhaps that is an easier question for the interwebnet to answer.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Idleater wrote: »
    Indeed, c decompiling is an art in itself. I wouldn't have the faintest idea where to start, but knew someone who was very good at it.

    What is it that you would like to understand from that program? Perhaps that is an easier question for the interwebnet to answer.

    We're doing a testing module ATM and our instructor gave us a .exe file to test and do test logs etc but I'm interested to see what the code looks like that's all really :p I love reading other people's code and trying to understand it.


  • Posts: 0 [Deleted User]


    I love reading other people's code and trying to understand it.

    Don't worry, the novelty will wear off.

    :D


  • Registered Users, Registered Users 2 Posts: 27,370 ✭✭✭✭GreeBo


    I love reading other people's code and trying to understand it.

    Wait until you have been coding a few years, then you get to look at crappy code and realise that the "other people" in this case are you. :eek::o


  • Registered Users, Registered Users 2 Posts: 6,262 ✭✭✭Buford T Justice


    We're doing a testing module ATM and our instructor gave us a .exe file to test and do test logs etc but I'm interested to see what the code looks like that's all really :p I love reading other people's code and trying to understand it.

    A decompiler won't give you a clean version of the code though, some of it would be garbage.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Just reviewing an exercise we were given and below is the instructors solution, I didn't have a chance to ask him, Can anyone tell me why he put int max = Integer.MIN_VALUE; and why int min = Integer.MAX_VALUE; I thought it would have been the other way round, int max = Integer.MAX_VALUE and min = Integer.MIN_VALUE, the program takes in 10 integers and gives back the min and max, the sum of the 10 numbers and the Average.
    import java.util.Scanner;
    
    public class TenStats {
    
    	private final int num_nums = 10;
    
    	public static void main(String[] args) {
    		new TenStats().getUpAndRun();
    	}
    
    	public void getUpAndRun() {
    		Scanner in = new Scanner(System.in);
    		int num = 0;
    		int max = Integer.MIN_VALUE;
    		int min = Integer.MAX_VALUE;
    		int tot = 0;
    		for(int i = 1; i <= num_nums; i++) {
    			System.out.print("Enter integer " + i + ": ");
    			num = in.nextInt();
    			tot += num;
    
    			if (num < min)min = num;
    
                if (num > max)max = num;
    
    
            System.out.println("\n\n");
    		System.out.println("Sum: " + tot);
    		System.out.println("Avg: " + tot / num_nums);
    		System.out.println("Max: " + max);
    		System.out.println("Min: " + min);
    		in.close();
    


  • Closed Accounts Posts: 1,758 ✭✭✭Pelvis


    Let's assume the following...

    Integer.MIN_VALUE = -999
    Integer.MAX_VALUE = 999

    Therefore your max is -999 and min is 999. Now let's say your first num input is 10.
    if (num < min)min = num;
    

    This would therefore be...
    if (10 < 999)min = 10;
    

    this evaluates to true and so your min value will be changed. If you initialized your min value to be Integer.MIN_VALUE, then if (num < min) will always evaluate to false, as no number you input will be less than the lowest possible number.

    Same logic with the max value.

    Have you done much debugging? Stepping through the code and seeing the variables change as you go really helps to clear up what's happening.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Pelvis wrote: »
    Let's assume the following...

    Integer.MIN_VALUE = -999
    Integer.MAX_VALUE = 999

    Therefore your max is -999 and min is 999. Now let's say your first num input is 10.
    if (num < min)min = num;
    

    This would therefore be...
    if (10 < 999)min = 10;
    

    this evaluates to true and so your min value will be changed. If you initialized your min value to be Integer.MIN_VALUE, then if (num < min) will always evaluate to false, as no number you input will be less than the lowest possible number.

    Same logic with the max value.

    Have you done much debugging? Stepping through the code and seeing the variables change as you go really helps to clear up what's happening.

    Cheers! makes sense.


  • Registered Users, Registered Users 2 Posts: 23,084 ✭✭✭✭Esel
    Not Your Ornery Onager


    Is your instructor following this thread? ;):D

    Not your ornery onager



  • Advertisement
  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    Esel wrote: »
    Is your instructor following this thread? ;):D

    Who knows :eek:


    *waves*


    :pac:


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    The code below basically takes in two numbers and there's a method that checks the first number entered isn't -1, then it should add both number and return the result, instead though it just keeps asking to enter a number until -1 is entered and then breaks out of the loop and then it asks for the second number, how do I get it to break out of the loop after a number is entered and add the two numbers together?
    public static int num1;
             static void Main(string[] args)
            {
                
                Boolean exit = true;
                
                while(exit){
                    num1= getNum1();
                    exit = checkNum(num1);
                    
                }
               
                int num2 = getNum2();
    
                int result = Add(num1,num2);
    
                Console.WriteLine("Result: " +Add(num1,num2));
               
            }
            public static int getNum1(){
                Console.WriteLine("Please enter a number: ");
                num1 = Convert.ToInt32(Console.ReadLine());
    
                return num1;
            }
            public static Boolean checkNum(int num1){
                if(num1 == -1){
                    Console.WriteLine("Exiting......");
                    return false;
                    
                }else{
                    return true;
                }
            }
            public static int getNum2(){
                Console.WriteLine("Please enter a second number: ");
                int num2 = Convert.ToInt32(Console.ReadLine());
    
                return num2;
            }
            public static int Add(int num1,int num2){
                 return num1+num2;
            }
            
        }
        
    }
    


  • Registered Users, Registered Users 2 Posts: 788 ✭✭✭pillphil


    What's the purpose of the loop and the check for -1?

    Should the program exit entirely if you enter -1?


  • Closed Accounts Posts: 2,910 ✭✭✭begbysback


    The only escape from the while loop is if -1 is entered - Checknum keeps returning true unless -1 is entered, therefore while loop keeps running


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    pillphil wrote: »
    What's the purpose of the loop and the check for -1?

    Should the program exit entirely if you enter -1?

    Yes it should exit entirely if -1 or less is entered,other it should continue on and ask for second number and then calculate them.


  • Registered Users, Registered Users 2 Posts: 788 ✭✭✭pillphil


    Yes it should exit entirely if -1 or less is entered,other it should continue on and ask for second number and then calculate them.

    In that case, do you need the loop? it would make sense if you were checking for non-numerical characters being entered, but since you're not, can you just remove it? or do you intent to add that functionality?


  • Registered Users, Registered Users 2 Posts: 6,262 ✭✭✭Buford T Justice


    The problem you're facing is an obvious one. Since you're learning I think that sometimes giving a nudge in the right direction is better than giving an answer. If you draw out and use pseudo code to describe the problem you're trying to solve the answer should become obvious. You might find you learn a lot more this way


  • Registered Users, Registered Users 2 Posts: 974 ✭✭✭Remouad


    So I think the first thing you need to do is define the problem.
    Are you trying you add 2 numbers once or repeatedly until -1 is entered

    As for the issue you're having the following bit of code is your problem
    while(exit){
                    num1= getNum1();
                    exit = checkNum(num1);
                    
                }
               
    

    This will keep looping, asking for the first number, until you enter -1 (exit=false)
    There is no logical path for adding the 2 numbers together.

    The following code will add the numbers in a loop until -1 is entered for the first number (note: num1 doesn't need to be static).
    public static void Main(string[] args)
            {
                int num1, num2;
                Boolean exit = true;
                while(exit){
                    num1= getNum1();
                    exit = checkNum(num1);
    
                    if(exit){            
                        num2 = getNum2();
        
                        Console.WriteLine("Result: " +Add(num1,num2));                
                    }else{
                        Console.WriteLine("Exiting");
                    }                 
                }
            }
               
    


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 81,083 Mod ✭✭✭✭Sephiroth_dude


    The problem you're facing is an obvious one. Since you're learning I think that sometimes giving a nudge in the right direction is better than giving an answer. If you draw out and use pseudo code to describe the problem you're trying to solve the answer should become obvious. You might find you learn a lot more this way

    This is a big problem for me, instead of sitting down and really analyzing the problem and writing it out I just jump in and try to write code straight away and it gets me nowhere.


  • Advertisement
  • Registered Users, Registered Users 2 Posts: 6,262 ✭✭✭Buford T Justice


    This is a big problem for me, instead of sitting down and really analyzing the problem and writing it out I just jump in and try to write code straight away and it gets me nowhere.

    If you want to improve as a developer, then this is a skill that you should learn. It'll be invaluable in the future.


Advertisement