java中的多字扫描仪输入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20141229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multi-word scanner input in java?
提问by Cataroux
So I'm trying to use if-else statement dependant upon the user's input. It works when the user's input is only one word, however, multiple word inputs go unrecognized and triggers the else statement. How can i resolve this?
所以我试图根据用户的输入使用 if-else 语句。当用户输入只有一个词时,它起作用,但是,多个词输入无法识别并触发 else 语句。我该如何解决这个问题?
import java.util.Scanner;public class MyFirstJavaClass {
public static void main(String[] args) { @SuppressWarnings("resource") Scanner myScanner = new Scanner(System.in); String answer; System.out.println("Catch the tiger or run away?"); answer = myScanner.next(); if (answer.equals("Catch the tiger" )) { System.out.println("You've been mauled by a tiger! What were you thinking?"); answer = myScanner.next(); } else { System.out.println("run away"); } } }
采纳答案by Sionnach733
Replace:
代替:
answer = myScanner.next();
With:
和:
answer = myScanner.nextLine();
next will only read in the next value until it reaches a space or newline. You want to read in the full line before making the comparison
next 只会读入下一个值,直到它到达一个空格或换行符。您想在进行比较之前阅读整行
回答by Mitaksh Gupta
try this :
尝试这个 :
Scanner scanner = new Scanner(System.in);
int choice = 0;
while (scanner.hasNext()){
if (scanner.hasNextInt()){
choice = scanner.nextInt();
break;
} else {
scanner.next(); // Just discard this, not interested...
}
}
Reference : Flush/Clear System.in (stdin) before reading
回答by ThomasEdwin
Try this
尝试这个
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
System.out.println("Catch the tiger or run away?");
if (myScanner.hasNext("Catch the tiger")) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
} else {
System.out.println("run away");
}
}
}