所以我试图使用依赖于用户输入的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"); } } }
答案 0 :(得分:5)
替换:
answer = myScanner.next();
使用:
answer = myScanner.nextLine();
接下来只会读取下一个值,直到它到达空格或换行符。在进行比较之前,您想要在整行中阅读
答案 1 :(得分:0)
试试这个:
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...
}
}
答案 2 :(得分:0)
试试这个
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");
}
}
}