我正在尝试制作一个简单的java程序,基本上我正在获取一些用户输入值并将其以整齐组织的输出打印出来。这一切都在控制台中。但是当我继续添加更多输入时,程序就不让我接受输入。这是我的代码:
import java.util.*;
public class output {
public static void main(String arg[]) {
//================================================================================
// Level 1 Start
//================================================================================
Scanner input = new Scanner(System.in);
//Start asking the user questions and store the values
System.out.println("Hello! What is your name?");
String name = input.nextLine();
System.out.println("Hello " + name + "! Nice to meet you!");
//================================================================================
// Level 1 End
//================================================================================
//================================================================================
// Level 2 Start
//================================================================================
System.out.println("How old are you?");
String age = input.nextLine();
System.out.println("Are you male or female?");
String gender = input.nextLine();
System.out.println("How much do you weigh?");
int weight = input.nextInt();
System.out.println("Are you a student? (true/false)");
boolean isAStudent = input.nextBoolean();
//Add a space
System.out.println("\n");
//Display the user's data neatly
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Gender: " + gender);
System.out.println("Weight: " + weight);
//check to see if the user is a student and print it out
if(isAStudent) {
System.out.println("Student?: Yes");
} else {
System.out.println("Student?: No");
}
//================================================================================
// Level 2 End
//================================================================================
//================================================================================
// Level 3 Start
//================================================================================
System.out.println("\n");
//display hello world a bunch of times
for(int i = 0; i < 5; i++){
System.out.println("Hello Hello Hello Hello Hello Hello");
}
System.out.println("\n");
System.out.println("Tell me a quote");
String quote = input.nextLine();
System.out.print(quote);
//================================================================================
// Level 3 End
//================================================================================
}
}
我知道我不应该在 stackoverflow 上放置大量代码,但我觉得其他部分可以找到解决方案。所以我的问题是,当我到达第 3 级(检查注释)并到达显示“告诉我报价”的打印语句时,我无法接受后面一行的输入。因此,字符串引用的输入就像我按下了回车键一样,即使我没有按下回车键。因此,在我能够输入任何内容之前它就获取了该值。请帮助我...如果您需要更多解释,请告诉我。
最佳答案
在此之后,
boolean isAStudent = input.nextBoolean();
缓冲区中保留有换行符。你应该摆脱它:
boolean isAStudent = input.nextBoolean();
input.nextLine();
关于Java简单程序不允许接受用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32408639/