0

If I have multiple Scanner user inputs, how can Scanner read an entire String with spaces? While I have seen multiple answers suggest using Scanner.nextLine(), I do not want to have to input the integer for choice and the String phrase on the same line (which is why I used switch, case instead of if/else) int choice = in.nextInt()

public static void main (String[] args){
Scanner in = new Scanner(System.in);
System.out.println ("welcome to November 1st Homework choices! if you would like to test the SSN condenser, input 1! if you would like to test the 'a' counter, input 2! If you would like to test both, enter 3!");
int choice = in.nextInt();
switch(choice){
  ...
  case 2:
     System.out.println("Please input a phrase of any sort to count the number of 'a''s in the phrase! :)");
     String phrase = in.next();
     System.out.println("The number of 'a's in the phrase is " + CountA(phrase));
    break;
  case 3:
    ...
    System.out.println("Please input a phrase of any sort to count the number of 'a''s in the phrase! :)");
    String phrase2 = in.next();
    System.out.println("The number of 'a's in the phrase is " + CountA(phrase2));
    break;
  default:
    System.out.println("YOU MUST ENTER A NUMBER BETWEEN 1 AND 3!! >:(D--");
    break;
}

}

I hope I made my question clear, I am quite confused.

Using String phrase = in.nextLine(); this is the 2 outputs

  • Why would you need to input choice and phrase on the same line? – luckydog32 Nov 02 '17 at 01:45
  • Keep choice the same and change this line in each of the switch statements: `String phrase = in.nextLine();`. – luckydog32 Nov 02 '17 at 01:46
  • What is the actual problem with your current code? – Tim Biegeleisen Nov 02 '17 at 01:47
  • When I run this code with `String phrase = in.nextLine()`, if I input 2 for choice, it will automatically run case 2 and use input 2 as the phrase and return that there are 0 'a's in the string. (2 is read both as the choice for the case and the literal string itself). The only way this has worked is if I input 2 AND right aftwerwards, I type in the phrase before I press enter – Mohammadou Gningue Nov 02 '17 at 01:49

1 Answers1

0

The reason you are having this issue is because when you hit enter there's an 'invisible' new line character that is created and not picked up by any other scanner method besides nextLine() on the first go. You can read more about it here.

Lets say you type 3 and hit enter. The scanner queue will look like this:

"3\n"

Then you use in.next();. The scanner takes the number but leaves the new line char:

"\n"

So when you get to your String phrase = in.next();. It will take that new line char as the input.

The solution is to catch it with a nextLine() and not do anything with it. So in your code it would look like:

int choice = in.nextInt();
in.nextLine(); //catch new line char
luckydog32
  • 909
  • 6
  • 13