Multi-word scanner input in java?

不羁岁月 提交于 2019-12-11 05:06:23

问题


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?

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

回答1:


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




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/20141229/multi-word-scanner-input-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!