[英]Java simple program not allowing to take user input
我正在嘗試制作一個簡單的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級(檢查注釋)並到達顯示“告訴我報價”的打印語句時,我無法在此之后進行輸入。 因此,即使我沒有輸入,String引號的輸入也表現為我按下了Enter鍵。 因此,在我什至無法鍵入任何內容之前就已經值了。 請幫助我...如果您需要更多說明,請告訴我。
在這之后,
boolean isAStudent = input.nextBoolean();
換行符保留在緩沖區中。 您應該擺脫它:
boolean isAStudent = input.nextBoolean();
input.nextLine();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.