Java util.Scanner无法立即识别用户输入

时间:2018-03-13 02:56:55

标签: java java.util.scanner

我是编程新手,我正在尝试用Java编写一个非常简单的程序。我希望给用户一个提示,给出两个选项来做什么,然后通过键入一个特定的单词选择两个选项中的一个,然后打印出指定的消息。

以下代码:

import java.util.Scanner;

public class coffeeProgram {

  public static void main(String[] args) {

    String Quit;
    String Coffee;

    Quit = "quit";
    Coffee = "coffee";

    System.out.println("You are sitting at your cubicle, staring at your computer screen.");
    System.out.println("What do you want to do?");
    System.out.println("Options: a) type 'coffee' to get a cup of coffee; or b) type 'quit' to quit your job");
    System.out.println("Enter an action:");

    Scanner input1 = new Scanner(System.in);
    String coffee = input1.next();
    String quit = input1.next();

    if (coffee.equals(Coffee)) {
      System.out.println("You stand up, and start walking to the coffee machine.");   
    }

    else if (quit.equals(Quit)) {
      System.out.println("You walk into your boss's office and say I QUIT");
    } 

    else {
      System.out.println("That's not a valid command");
    }
    input1.close();    
  }
}

我遇到的问题是,在初始提示输出后,程序似乎不会确认用户输入,除非您输入所需的单词,点击返回,然后返回其他一些字符。例如,一个选择的单词是“coffee”,但是如果我输入“coffee”后跟返回键,则没有任何反应,除非我输入一些字符然后再返回。

根据我所做的研究,我认为我的问题与扫描仪在用户输入所需单词后无法识别返回键有关。为什么这不起作用?

4 个答案:

答案 0 :(得分:1)

问题出在这些方面

String coffee = input1.next();
  String quit = input1.next();

您的代码需要两个输入。不应将coffeequit视为两个单独的变量,而应该阅读该选项,然后执行if..else

这样的东西
String choice = input1.next();

if (choice.equals(Coffee)) {
    System.out.println("You stand up, and start walking to the coffee machine.");   
}

 else if (choice.equals(Quit)) {
    System.out.println("You walk into your boss's office and say I QUIT");
} 

答案 1 :(得分:1)

这是因为您使用了 input1.next(); 两次。

//create Scanner instance
Scanner input1 = new Scanner(System.in); 
//wait NEXT input
String coffee = input1.next();
//wait another NEXT input
String quit = input1.next();

程序正在等待两个输入,然后才能给你一些响应。

所以,正确的方法应该是这样的。

//create Scanner instance
Scanner input1 = new Scanner(System.in); 
//wait NEXT one input
String command = input1.next();
//compare input with predefined commands
if(command.equals(Coffee)){

}else if(command.equals(Quit)){

}else{

}

答案 2 :(得分:0)

您的问题是您将两个变量分配给一行输入,咖啡和退出。所以你只需摆脱String quit = input1.next();行并将else if (quite.equals(Quit)) {更改为else if (coffee.equals(Quit)) {。所有这些意味着你的输入是在咖啡中,你从它们收集的输入无关紧要,它只需要在一个变量中,然后你可以使用该变量来查看它是否等于退出,咖啡或它是否无效。

希望我能帮助你更好地理解它。

答案 3 :(得分:0)

我认为你应该定义一个String参数。

然后你应该使用nextLine()来获取像这样的

String choices = input1.nextLine();

然后如果......其他