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

Finding smaller number of 2 numbers inputted by user

Options
1246

Comments

  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,011 Mod ✭✭✭✭Sephiroth_dude


    If you put final static does that mean the value of age never changes?
    final static int age = 24;
    


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


    If you put final static does that mean the value of age never changes?
    final static int age = 24;
    

    Final, means no changes once set. Static means one instance of that object is shared among all instances of the class.


  • Registered Users Posts: 974 ✭✭✭Remouad


    Bonus info:

    Declaring a class as final means it can't be inherited.

    Declaring a method as final means that it can't be overridden by an inheriting class.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,011 Mod ✭✭✭✭Sephiroth_dude


    Remouad wrote: »
    Bonus info:

    Declaring a class as final means it can't be inherited.

    Declaring a method as final means that it can't be overridden by an inheriting class.

    Decent info there Remouad cheers!


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,011 Mod ✭✭✭✭Sephiroth_dude


    Having a problem with the loop in this program, if I choose option 1, 2 or 3 it will just go into continuous loop and won't stop and I have to exit eclipse to get to stop, any idea? I tried a while loop before trying do and same issue.

    int Choice = 0;
    		Scanner sc = new Scanner(System.in);
    		
    		System.out.println("Please Pick an option by pressing 1,2,3 or 0 to Exit the program");
    		Choice = sc.nextInt();
    		
    		
    		do{
    			
    			
    			switch(Choice)
    			{
    			case 1:
    			System.out.println("Mr.Red");
    			MrRed();
    			break;
    			
    			case 2:
    			System.out.println("Mr.Blue");
    			MrBlue();
    			break;
    			
    			case 3:
    			System.out.println("Mr.Green");
    			MrGreen();
    			break;
    			
    			case 0:
    			System.out.println("Thank you and goodbye!");
    			break;
    			
    			default:
    				System.out.println("Not a vaild selection!");
    				break;
    			
    				
    			}
    		
    		}while(Choice != 0);
    		
    		
    		
    		
    	}
    
    	
    	
    	
    	public static void MrRed()
    	{
    		System.out.println("Hello Mr  Red");
    	}
    	
    	public static void MrBlue()
    	{
    		System.out.println("Hello Mr  Blue");
    	}
    	
    	public static void MrGreen()
    	{
    	    System.out.println("Hello Mr  Green");
    	}
    	
    	
    }
    


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


    if I choose option 1, 2 or 3 it will just go into continuous loop

    int Choice = 0;
    		
    		Choice = sc.nextInt();
    		
    		
    		do{
    			
    			
    		}while(Choice != 0);
    		
    		
    		
    		
    	}
    
    	
    	
    }
    

    You only read in the input once, and then do...while (or while ... do).

    You somehow need to allow the Choice variable to be updated during the loop.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,011 Mod ✭✭✭✭Sephiroth_dude


    Idleater wrote: »
    You only read in the input once, and then do...while (or while ... do).

    You somehow need to allow the Choice variable to be updated during the loop.

    Should getting the input be within the loop instead of outside it?


  • Registered Users Posts: 974 ✭✭✭Remouad


    Should getting the input be within the loop instead of outside it?

    Yep.
    Otherwise the value will be the same for each iteration.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,011 Mod ✭✭✭✭Sephiroth_dude


    When I was using visual studio on my last course when you ran a program it would run it via the command prompt, is it possible to do that in eclipse instead of having programs output to the console?


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,011 Mod ✭✭✭✭Sephiroth_dude


    Just wondering lets say you want the user to enter in a username and password in order for them to progress with the program is it possible in java to have an external file with names and passwords and read them in that way? so if the user typed in a name or password and it didn't exist in the external file you'd get an error message? I'm guessing you would need two files? one for passwords and one for usernames?


  • Advertisement
  • Registered Users 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 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: 80,011 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: 80,011 Mod ✭✭✭✭Sephiroth_dude


    Sorted, changed double hoursworked to this.hoursworked.


  • Moderators, Computer Games Moderators, Social & Fun Moderators Posts: 80,011 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: 80,011 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: 80,011 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: 80,011 Mod ✭✭✭✭Sephiroth_dude


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

    Thanks so much that, helps a lot.


  • Registered Users Posts: 6,250 ✭✭✭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: 80,011 Mod ✭✭✭✭Sephiroth_dude


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


  • Registered Users 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: 80,011 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 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: 80,011 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 Posts: 6,013 ✭✭✭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.


Advertisement