Results 1 to 9 of 9
  1. #1
    tonmachine is offline Member
    Join Date
    Feb 2013
    Posts
    5
    Rep Power
    0

    Default Switch statement not working

    Hello, I am VERY new to Java and I am trying to write a switch statement in which, if the user enters a number, he or she is prompted to enter a second number. If the user enters anything but a number, the program outputs a message and then exits. Whenever I run this having the user input something besides a number, it just gives me the java.util.InputMismatchException line and doesn't output and exit like I want it to. Does someone know what I need to tweak to get this to run correctly? Thanks!!

    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter any number.");
    int n1 = keyboard.nextInt();

    switch (n1) {

    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
    case 7:
    case 8:
    case 9: System.out.println("Enter a second number.");
    break;
    default: System.out.println("That is not a number. Goodbye!");
    System.exit(0);
    }

  2. #2
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    6

    Default Re: Switch statement not working

    keyboard.nextInt() expects a number. If you enter something else the InputMismatchException is thrown. Use keyboard.nextLine() to get the input as a String.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,564
    Rep Power
    23

    Default Re: Switch statement not working

    java.util.InputMismatchException
    That message is from the Scanner looking at the user's input and not finding an int. Using the nextInt() method will have the method checking the user's input. The Scanner class has other methods that will allow the user to enter anything instead of only integer input. Also the Scanner class has methods (names begin with has) to test what the user has entered. These could be called to see what type of data the user has entered.
    If the user's input is read into a String there are methods that can be used to test if the contents of the String is numeric.
    If you don't understand my response, don't ignore it, ask a question.

  4. #4
    tonmachine is offline Member
    Join Date
    Feb 2013
    Posts
    5
    Rep Power
    0

    Default Re: Switch statement not working

    Thanks! That makes sense, but later on I am supposed to use this input (along with six other numbers that the user puts in) to find largest number, smallest number, average, and totals. I know how to do this with int but how can I do this if the computer is reading the user's input as a string?

  5. #5
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    6

    Default Re: Switch statement not working

    It boils down to forcing the user to enter numbers. Either you catch the exception and let him reenter, or you try to convert the input into a number and if that fails you let the user reenter.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,564
    Rep Power
    23

    Default Re: Switch statement not working

    The Integer class has a method to convert a String to an int.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    SnakeDoc is offline Senior Member
    Join Date
    Apr 2012
    Posts
    129
    Rep Power
    0

    Default Re: Switch statement not working

    Here's a common way I use to validate user input for correctness:

    Java Code:
    Scanner keyboard = new Scanner(System.in);
     
    boolean isNotCorrect = true;
    String userInput = "";
    int userInt = 0;
     
    while (isNotCorrect) {
        System.out.print("Please enter an integer number: ");
        userInput = keyboard.nextLine();  // nextLine() method of Scanner gets any input and stores as string value
        try {
            userInt = Integer.parseInt(userInput);  // Integer is the integer object, as apposed to the primitive data type int. The Integer object 
                                                    //allows you to do nice things like convert a string object to an integer - with the parseInt() method. 
                                                    //There are many other things Integer can do, I suggest googleing "Integer java" and reading up on the docs.
    
            isNotCorrect = false;   // if Integer.parseInt() does not throw an exception (due to invalid conversion of string to int such 
                                    //as the letter "J" or something), then we have a correct input value
    
        } catch (NumberFormatException e) {     // if Integer.parseInt() throws an exception (due to invalid conversion) 
                                                //then we need to ask the user to try again, so make sure the loop repeats by 
                                                //setting our test condition (isNotCorrect) to true. 
    
            System.out.println("You did not enter a valid integer number! Try again please!");
            isNotCorrect = true;
        }
    }
    Not sure if you have covered the try/catch blocks yet in your class... if not this may be more advanced than what your professor wants... you can find out what exception a method throws by checking the Java docs (I usually google the class and method names such as Integer.parseInt() and google will usually return the doc as the first link... )

    Good luck!
    Last edited by SnakeDoc; 02-06-2013 at 05:24 PM. Reason: added line comments for clarity...

  8. #8
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    6

    Default Re: Switch statement not working

    Nice spoon feeding.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  9. #9
    SnakeDoc is offline Senior Member
    Join Date
    Apr 2012
    Posts
    129
    Rep Power
    0

    Default Re: Switch statement not working

    its a design pattern that he/she may learn from (hence the heavily commented lines). Sometimes learning from someone else's work helps grasp the concept a lot quicker... And besides, they still have to figure out how to implement it into their program since they appear to have to use the SWITCH statement structure... so this isn't an exact "plug-n-play" solution.

Similar Threads

  1. Replies: 3
    Last Post: 11-19-2012, 08:12 PM
  2. Replies: 2
    Last Post: 03-26-2012, 04:27 PM
  3. switch statement
    By droidus in forum New To Java
    Replies: 2
    Last Post: 09-21-2011, 09:54 AM
  4. help with switch statement
    By java__beginner in forum New To Java
    Replies: 4
    Last Post: 03-19-2009, 02:22 PM
  5. Switch Statement Help
    By bluegreen7hi in forum New To Java
    Replies: 6
    Last Post: 02-06-2008, 05:16 AM

Tags for this Thread

Posting Permissions

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