我正在使用 Eclipse 和 JDK 8 创建一个用 Java 编写的程序。我使用以下代码创建了一个 Scanner
:Scanner input = new Scanner(System.in);
然后我使用代码 String
创建了一个 String command = "no";
我计划使用此字符串来控制代码中的 while
循环,以及 switch
循环内的 while
。循环以: while(command = "no")
开始,在 while
循环中,我使用之前创建的 Scanner
来让用户定义 String
和 int
的值,这些值在执行代码时起作用。之后(但仍在 while
循环内,我在下面的行中输入 command = input.nextLine();
,后跟 input.close();
,以设置 command
字符串的值,并关闭 Scanner
。但是当我执行代码时,它似乎跳过了这一点,并且我直接放在后面的 switch
(也应该由 command
字符串控制),并继续在 while
循环之后编写代码,即使 command
仍然设置为“no”,这应该使 while
循环再次开始。
如何使代码暂停并等待在 command = input.nextLine();
处输入内容,以及如何使 switch
正常工作?
完整代码如下:
`导入java.util.Scanner;
class Human {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
String name = this.name;
return name;
}
public int getAge() {
int age = this.age;
return age;
}
}
public class Asdfghjkl {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String command = "no";
int age;
String name;
while(command == "no") {
System.out.println("Welcome to HUMAN CREATOR");
System.out.println("What is the human's name?");
name = input.nextLine();
System.out.println("Okay, its name is " + name + ".");
System.out.println("What about its age?");
age = input.nextInt();
System.out.println(name + " is " + age + " years old.");
System.out.println("Is this correct?");
command = input.nextLine();
switch (command) {
case ("yes"):
System.out.println("Great! Lets make the human!");
Human h1 = new Human();
h1.setAge(age);
h1.setName(name);
case ("no"):
System.out.println("Okay, lets start again.");
}
}
System.out.println("qwerty");
input.close();
}
}
最佳答案
更改您的:
age = input.nextInt();
致:
age = Integer.parseInt(input.nextLine());
“nextInt()”无法正常工作的原因是它在队列中留下了一个空白空间,该空间在下一个“nextLine()”处被挑选出来
此外,在比较两个字符串时,您应该始终使用 .equals("some string")。
我希望这可以解决您的错误:)
正如“Hovercraft Full Of Eels”所指出的,如果您确实需要重复 while 循环,扫描仪将关闭,因此会导致错误。
关于Java 代码不等待扫描仪输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22800422/