我对编程完全陌生,我正在尝试用 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”并按回车键,则除非我输入某个字符并再次按回车键,否则不会发生任何情况。
根据我所做的研究,我认为我的问题与用户输入所需单词后扫描仪无法识别返回键有关。为什么这不起作用?
最佳答案
问题就在这几行
String coffee = input1.next();
String quit = input1.next();
您的代码需要两个输入。您不应将 coffee
和 quit
作为两个单独的变量来读取,而应该读取选择,然后执行 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");
}
关于Java util.Scanner 无法立即识别用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49247597/