不要求输入

Ste*_*ven 4 java

我有这个:

Scanner input = new Scanner ( System.in );
int selection = input.nextInt();
if (selection == 1) {
System.out.println("Please enter a string: ");
String code = input.nextLine();
}
Run Code Online (Sandbox Code Playgroud)

但是,当它输入请输入字符串时,它不会要求任何输入.它只是进入程序的其余部分.

Mar*_*ers 7

Scanner在等待,nextInt()直到用户按下输入.当发生这种情况时,它会消耗数字,但不会消耗新的行字符本身.因此,下一次调用nextLine()立即返回,String结果为空.

这应该解决它:

int selection = input.nextInt();
input.nextLine();
if (selection == 1) {
   System.out.println("Please enter a string: ");
   String code = input.nextLine();
Run Code Online (Sandbox Code Playgroud)

但我首选的方法是始终使用nextLine并单独进行解析:

String selectionStr = input.nextLine();

//consider catching a NumberFormatException here to handle erroneous input
int selection = Integer.parseInt(selectionStr); 

if (selection == 1) {
   System.out.println("Please enter a string: ");
   String code = input.nextLine();
   //...
Run Code Online (Sandbox Code Playgroud)