Results 1 to 19 of 19
Like Tree5Likes
  • 1 Post By Norm
  • 2 Post By pbrockway2
  • 1 Post By sunde887
  • 1 Post By Junky

Thread: What variable type should I use?

  1. #1
    Eleeist is offline Member
    Join Date
    May 2011
    Posts
    84
    Rep Power
    0

    Default What variable type should I use?

    I want to make a simple calculator. The user enters two numbers and then has a choice of either adding or subtracting them. Here is the code:

    PHP Code:
    import java.util.Scanner;
    
    class apples {
    	public static void main(String[] args){
    		
    		double firstNumber;
    		double secondNumber;
    		double answer;
    		char choice;
    		
    		Scanner userInput = new Scanner(System.in);
    		
    		System.out.println("Enter the first number: ");
    		firstNumber = userInput.nextInt();
    		
    		System.out.println("Enter the second number: ");
    		secondNumber = userInput.nextInt();
    		
    		System.out.println("Enter your choice (add or substract): ");
    		choice = userInput.nextChar();
    
    	}
    }
    Of course, the userInput.nextChar() is invalid. Why? What should I use instead?

    Thanks

  2. #2
    Dark's Avatar
    Dark is offline Senior Member
    Join Date
    Apr 2011
    Location
    Camp Lejuene, North Carolina
    Posts
    643
    Rep Power
    4

    Default

    nextDouble()? If your variables are doubles, then use the appropriate input type for your scanner. If you use nextInt you will put Ints into your doubles. Read the API.

    I believe for the add or subtract option, you're looking for nextLine().

    Scanner (Java Platform SE 6)
    • Use [code][/code] tags when posting code. That way people don't want to stab their eyes out when trying to help you.
    • +Rep people for helpful posts.

  3. #3
    Eleeist is offline Member
    Join Date
    May 2011
    Posts
    84
    Rep Power
    0

    Default

    Egh, the Int instead of double is embarrasing...

    If I put nextLine(), I think I have to change the variable type to something else than "char", right..?

  4. #4
    Eleeist is offline Member
    Join Date
    May 2011
    Posts
    84
    Rep Power
    0

    Default

    I googled some things and here is the modified version of the code, completed with if and else statements.

    PHP Code:
    import java.util.Scanner;
    
    class calculator {
    
    	public static void main(String[] args){
    	
    	double firstNumber;
    	double secondNumber;
    	double answer = 0;
    	String add = "add";
    	String subtract = "subtract";
    		
    	Scanner userInputInt = new Scanner(System.in);
    	System.out.println("Enter the first number:");
    	firstNumber = userInputInt.nextDouble();
    	System.out.println("Enter the second number:");
    	secondNumber = userInputInt.nextDouble();
    	
    	Scanner userInputString = new Scanner(System.in);
    	System.out.println("What do you want to do (add or subtract)?");
    	String choice = userInputString.nextLine();
    	
    	
    	if (choice == add) {
    	
    		answer = firstNumber + secondNumber;
    		
    		}
    		
    	else if (choice == subtract) {
    	
    		answer = firstNumber - secondNumber;
    		
    		}
    		
    	else {
    	
    		System.out.println("Unknown input. Try again.");
    		
    		}
    		
    	System.out.println(answer);
    	
    	}
    
    }
    However the code always prints "Unknown input. Try again." no matter if I type add or subtract. Also I tried to compare words add and subtract directly to choice variable, but this did not work so I decided to put these words in variables add and subtract. Either way it does not work. Any help will be appreciated :)

    PS: worth noting: when printing choice variable directly for debugging it prints exactly what I type, so it should work as it is exactly either add or subtract.
    Last edited by Eleeist; 07-28-2011 at 12:58 AM.

  5. #5
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    Don't compare strings with ==. Use the string equals() method. This is a general point that applies to anything, not just instances of String. All classes have an equals() method that will return true when two things can be considered equal. == means something more like "identical". Eg the third word in this sentence is equal to the third to last. Ie they are made up of the same sequence of characters, but they are not identical because one is near the start and the other is near the end of the sentence so they are clearly distinct (nonidentical).

    -----

    A separate point - that is, deal with it after the first one - is that you don't really need two scanners.

  6. #6
    stchman's Avatar
    stchman is offline Member
    Join Date
    Apr 2011
    Location
    Saint Louis, Missouri
    Posts
    97
    Rep Power
    0

    Default

    Quote Originally Posted by Eleeist View Post
    I want to make a simple calculator. The user enters two numbers and then has a choice of either adding or subtracting them. Here is the code:

    PHP Code:
    import java.util.Scanner;
    
    class apples {
        public static void main(String[] args){
            
            double firstNumber;
            double secondNumber;
            double answer;
            char choice;
            
            Scanner userInput = new Scanner(System.in);
            
            System.out.println("Enter the first number: ");
            firstNumber = userInput.nextInt();
            
            System.out.println("Enter the second number: ");
            secondNumber = userInput.nextInt();
            
            System.out.println("Enter your choice (add or substract): ");
            choice = userInput.nextChar();
    
        }
    }
    Of course, the userInput.nextChar() is invalid. Why? What should I use instead?

    Thanks
    I would personally use the next() method of Scanner. It returns a String so you can then use the Double.parseDouble( String ) method. This would give you better control over things. Also, make sure you try - catch the parseDouble method to make sure the user enters a parseable number.

    There is no nextChar() method in the scanner class.

  7. #7
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    Quote Originally Posted by stchman View Post
    I would personally use the next() method of Scanner. It returns a String so you can then use the Double.parseDouble( String ) method.
    Why? You can just use the nextInt or nextDouble methods.

    To get the user input as a char you can use the next or nextLine method and then call charAt on the String to get the first (and possibly only) char.

  8. #8
    stchman's Avatar
    stchman is offline Member
    Join Date
    Apr 2011
    Location
    Saint Louis, Missouri
    Posts
    97
    Rep Power
    0

    Default

    For the OP's 2nd attempt he needs to compare Strings using the .equals method.

    Use:
    Java Code:
    if( choice.equals( "add" ) == true ) {
        // code here
    }
    I know some don't want to use the == true, but the .equals() method RETURNS a boolean!!!!!!!!

    String API Java 6

  9. #9
    stchman's Avatar
    stchman is offline Member
    Join Date
    Apr 2011
    Location
    Saint Louis, Missouri
    Posts
    97
    Rep Power
    0

    Default

    Quote Originally Posted by Junky View Post
    Why? You can just use the nextInt or nextDouble methods.

    To get the user input as a char you can use the next or nextLine method and then call charAt on the String to get the first (and possibly only) char.
    There are many ways to do the same thing in Java.

  10. #10
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    Yes so the the comparison to true is pointless.

  11. #11
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    Quote Originally Posted by stchman View Post
    There are many ways to do the same thing in Java.
    Yes and you seem intent on providing less than optimum solutions/suggestions/help.

  12. #12
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,874
    Rep Power
    25

    Default

    What does the == operator return?
    Isn't testing == true redundant?
    Where do you stop:
    if( ((choice.equals( "add" ) == true ) == true) == true) {

    A problem with this technique is that if a student leaves off one of the = and ends up with an assignment statement.
    This can be really hard to see.
    Last edited by Norm; 07-28-2011 at 03:41 AM.
    sunde887 likes this.

  13. #13
    stchman's Avatar
    stchman is offline Member
    Join Date
    Apr 2011
    Location
    Saint Louis, Missouri
    Posts
    97
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    What does the == operator return?
    Isn't testing == true redundant?
    Where do you stop:
    if( ((choice.equals( "add" ) == true ) == true) == true) {

    A problem with this technique is that if a student leaves off one of the = and ends up with an assignment statement.
    This can be really hard to see.
    The statement is also handy if one wants to see if a string is not equal to another string.

    Java Code:
    if( choice.equals( "add" ) == false ) {
        // do somehting
    }
    Yes I know one can use
    if( choice.equals( "add" ) )
    or
    if( !choice.equals( "add" ) )

    I just find my way more clear, just a preference.

  14. #14
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    I guess you prefer
    Java Code:
    int x = 10;
    x = 10;
    Just to be sure!

  15. #15
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    No, just being sure would involve the "really really true" superboolean:

    Java Code:
    if( choice.equals( "add" ) == !!!!!!true ) {
    I'm surprised no-one has suggested swapping choice and "add".

    -----

    Seriously, redundancy tends to result in less clarity as the reader has to stop, ponder what tricky thing might be going on, and only be above to move on when they've figured out that nothing at all is going on.
    Norm and kjkrum like this.

  16. #16
    Eleeist is offline Member
    Join Date
    May 2011
    Posts
    84
    Rep Power
    0

    Default

    Sorry for delay...

    So, here is modified code that works (yupi!!):

    PHP Code:
    import java.util.Scanner;
    
    class apples {
    
        public static void main(String[] args){
        
        double firstNumber;
        double secondNumber;
        double answer = 0;
            
        Scanner userInputInt = new Scanner(System.in);
        System.out.println("Enter the first number:");
        firstNumber = userInputInt.nextDouble();
        System.out.println("Enter the second number:");
        secondNumber = userInputInt.nextDouble();
        
        Scanner userInputString = new Scanner(System.in);
        System.out.println("What do you want to do (add or subtract)?");
        String choice = userInputString.nextLine();
        
        
        if (choice.equals("add") == true) {
        
            answer = firstNumber + secondNumber;
            
            }
            
        else if (choice.equals("subtract") == true) {
        
            answer = firstNumber - secondNumber;
            
            }
            
        else {
        
            System.out.println("Unknown input. Try again.");
            
            }
            
        System.out.println(answer);
        
        }
    
    }
    Quote Originally Posted by pbrockway2 View Post
    A separate point - that is, deal with it after the first one - is that you don't really need two scanners.
    If I do this:

    PHP Code:
    import java.util.Scanner;
    
    class apples {
    
        public static void main(String[] args){
        
        double firstNumber;
        double secondNumber;
        double answer = 0;
            
        Scanner userInput = new Scanner(System.in);
        System.out.println("Enter the first number:");
        firstNumber = userInput.nextDouble();
        System.out.println("Enter the second number:");
        secondNumber = userInput.nextDouble();
        System.out.println("What do you want to do (add or subtract)?");
        String choice = userInput.nextLine();
        
        
        if (choice.equals("add") == true) {
        
            answer = firstNumber + secondNumber;
            
            }
            
        else if (choice.equals("subtract") == true) {
        
            answer = firstNumber - secondNumber;
            
            }
            
        else {
        
            System.out.println("Unknown input. Try again.");
            
            }
            
        System.out.println(answer);
        
        }
    
    }
    After inputting two numbers the console throws a "Unknown input. Try again" at me without even asking me for entering my choice.

    I read somewhere that using both numbers and strings in one scanner is not a good idea, so I created a second scanner and it worked.

  17. #17
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    The problem with using scanners for numbers and strings is that many of the scanner methods get the next token. So if you use nextInt, or a similar method, it gets the next int, but leaves everything after the line intact.

    Java Code:
    input of "1.0 5 10.0
    scan.nextDouble() //returns 1.0 and leaves "5 10 10.0"
    scan.nextInt() //returns 5 and leaves "10 10.0"
    scan.nextInt() //returns 10 and leaves "10.0"
    scan.nextDouble() //returns 10.0 and returns ""
    Which actually has a new line character hanging on the end. So generally you can cause problems by doing something like calling nextDouble again, since it will grab the next line character and cause problems.

    Try doing either of the following things, after each call of nextInt, nextDouble, next, etc, follow it by a call to nextLine() to "swallow" the new line character.

    or

    stick to using nextLine, and parse the input with methods like Integer.parseInt(...), and Double.parseDouble(...), etc
    pbrockway2 likes this.

  18. #18
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    Java Code:
    if (choice.equals("add") == true) {
    It's amazing how many times people read the bad advice and totally ignore the good advice.
    sunde887 likes this.

  19. #19
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Quote Originally Posted by Junky View Post
    Java Code:
    if (choice.equals("add") == true) {
    It's amazing how many times people read the bad advice and totally ignore the good advice.
    Can't agree with this statement more. I implore you to not do this as stated in this thread. Doing simply
    Java Code:
    if(choice.equals("String"))
    instead. The other approach is really a poor habit to get into and doesn't make much sense, the == operator returns a boolean, as does the equals method, do why test the boolean value returned from the equals method? If the strings match, equals will return true, and the if statement will have a true, otherwise it will be false.

Similar Threads

  1. Print variable data type
    By BillyB in forum New To Java
    Replies: 1
    Last Post: 01-14-2011, 05:37 PM
  2. do while (variable != type)
    By Romally in forum New To Java
    Replies: 2
    Last Post: 11-15-2010, 06:29 AM
  3. Replies: 1
    Last Post: 12-09-2009, 01:57 AM
  4. using instanceof to get Object type and parent type?
    By xcallmejudasx in forum New To Java
    Replies: 2
    Last Post: 11-06-2008, 07:24 PM
  5. [SOLVED] curiosity about String type variable
    By monir6464 in forum Advanced Java
    Replies: 1
    Last Post: 04-08-2008, 12:13 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •