[英]How to get the Java Scanner utility to input twice
所以继承人我的代码
public class Practice01{
public static void main (String[] args){
System.out.println("Hi there");
Scanner scr = new Scanner(System.in);
String response = scr.nextLine();
if (response.equalsIgnoreCase("hello") || response.equalsIgnoreCase("hi") || response.equalsIgnoreCase("hey")) {
System.out.println("Oh, well arent you well-mannered. Hello there, how are you?");}
else {
System.out.println("Invalid Input");
String responseG;
responseG = scr.nextLine();
if (responseG.equalsIgnoreCase("good")) {
System.out.println("Glad to hear");
}
}
}
}
说到java,我有点菜鸟,我今天刚开始,但是在这里的else语句之后,java由于某种原因自行终止,它只是不关心其余的代码。 我在网上看,我看到如果你想接受另一个输入,你使用了.nextLine();
函数(我不认为它被称为函数,但你知道我的意思)但是在我输入 hey、hello 或 hi 后,它会打印“哦,你不是很有礼貌。你好,你好吗?” 然后我无法输入任何其他内容,它说 < 终止 > 。 有人可以帮忙吗? 谢谢
编辑:显然我应该将“responseG”变量和下一行移动到 if 语句中。 当我这样做时,它不会激活,(使用 eclipse IDE,它只是显示为白色和错误)并告诉我删除其他。 https://gyazo.com/1a27fa9ab8802d594cccb35ecc0cb663图片发生了什么。 此外,如果我尝试使用 else if 语句,它也会说要删除它
您必须使用循环来保持程序运行。 在你听到“哦,你不是很有礼貌吗。你好,你好吗?” 打印,它终止了没有更多任务要做的事实。
如果您不输入“hello”或“Hello”或“hey”,您的程序只会要求您从键盘输入另一个输入,您知道我的意思。 如果你输入“hello”,它会打印一行
“哦,你是不是很有礼貌。你好,你好吗?”
并且程序将被终止...
这就是你的代码告诉你的程序要做的事情,因为你只是在 else 语句的主体中要求另一个输入。
正如我所看到的,你不想使用 for 循环,因为你似乎只关心一条说 hi 的路径......你好吗?......很好......很高兴听到......但是如果你关心它,您可以使用while()
语句或do..while()
或for()
使其在变量中保存许多使用scr.nextLine();
响应scr.nextLine();
函数(它是一个函数),在这种情况下,您必须定义程序何时/如何停止请求输入并终止。
我相信这就是你想要做的,使用适当的缩进,而不是声明不必要的变量:
public class Practice01{
public static void main (String[] args){
System.out.println("Hi there");
Scanner scr = new Scanner(System.in);
String response = scr.nextLine();
if (response.equalsIgnoreCase("hello") || response.equalsIgnoreCase("hi") || response.equalsIgnoreCase("hey")) {
System.out.println("Oh, well arent you well-mannered. Hello there, how are you?");
}
else {
System.out.println("Invalid Input");
}
//You don't need ResponseG... you've already created the response variable
response = scr.nextLine();
if (response.equalsIgnoreCase("good")) {
System.out.println("Glad to hear");
}
else {
System.out.println("Invalid Input");
}
}
}
所以你想要做的是将 ResponseG if 语句移动到你的响应 if 语句中,因为这会阻止代码完成,因为你输入了正确的输入。 同样对于未来的项目,为了更有条理,在代码的开头创建变量。
public class Practice01{
public static void main (String[] args){
System.out.println("Hi there");
String responseG;
Scanner scr = new Scanner(System.in);
String response = scr.nextLine();
if (response.equalsIgnoreCase("hello") ||
response.equalsIgnoreCase("hi") ||
response.equalsIgnoreCase("hey")) {
System.out.println("Oh, well arent you well-mannered. Hello there, how are you?");
responseG = scr.nextLine();
if (responseG.equalsIgnoreCase("good")) {
System.out.println("Glad to hear");
}
} else {
System.out.println("Invalid Input");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.