java中的多字扫描仪输入



因此,我尝试使用依赖于用户输入的if-else语句。当用户的输入只有一个单词时,它就工作了,但是,多个单词的输入无法识别并触发else语句。我该如何解决此问题?

导入java.util.Scanner;

公共类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"); } } }

替换:

answer = myScanner.next();

带有:

answer = myScanner.nextLine();

next将只读取下一个值,直到它到达空格或换行符。在进行比较之前,您需要阅读整行

试试这个:

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...
    }
}

参考:在读取之前刷新/清除System.in(stdin)

试试这个

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");
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新