简体   繁体   English

具有不同输入类型的连续嵌套扫描器,包括带空格的字符串

[英]Consecutive nested Scanners with different input types including a string with spaces

If I have multiple Scanner user inputs, how can Scanner read an entire String with spaces? 如果我有多个Scanner用户输入,Scanner如何读取带空格的整个字符串? 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() 虽然我看到有多个答案建议使用Scanner.nextLine() ,但我不想输入整数作为choice ,而在同一行输入String phrase (这就是为什么我使用switch, case而不是if/elseint 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(); 使用String phrase = in.nextLine(); this is the 2 outputs 这是2个输出

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. 出现此问题的原因是,当您按Enter键时,会创建一个“不可见”换行符,并且该字符不会被初次使用nextLine()之外的其他任何扫描程序方法拾取。 You can read more about it here . 您可以在此处了解更多信息。

Lets say you type 3 and hit enter. 假设您输入3,然后按Enter。 The scanner queue will look like this: 扫描程序队列如下所示:

"3\n"

Then you use in.next(); 然后使用in.next(); . The scanner takes the number but leaves the new line char: 扫描程序获取数字,但保留新行char:

"\n"

So when you get to your String phrase = in.next(); 因此,当您到达String phrase = in.next(); . It will take that new line char as the input. 它将以该新行char作为输入。

The solution is to catch it with a nextLine() and not do anything with it. 解决方案是使用nextLine()捕获它,而不对其执行任何操作。 So in your code it would look like: 因此,在您的代码中,它看起来像:

int choice = in.nextInt();
in.nextLine(); //catch new line char

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM