在 Java 中按 Enter 繼續
本文將向你展示我們如何將控制檯置於暫停狀態,直到使用者按下 Enter,然後才會顯示下一條訊息。在以下示例中,我們將使用 Scanner 類獲取三個輸入,然後將它們顯示在控制檯上。
在 Java 中使用額外的 nextLine() 等待 Enter 鍵
在示例中,我們建立了一個 Scanner 類的物件,即 sc。Scanner 掃描文字並解析原始型別,如 int 和 String。這個類帶有很多用於輸入操作的方法。最常用的方法是 nextInt()、nextLine、nextDouble 等。
在下面的示例中,我們將看到問題所在,並在下一個示例中使用一種技術來解決它。
在這裡,我們採用三個輸入:int 型別,接下來的兩個是 String 型別。我們使用 Scanner 類首先呼叫 nextInt() 方法將年齡的輸入輸入到 int 型別變數中;然後,為了輸入名字和姓氏,我們使用兩個 sc.nextLine() 方法和兩個變數來儲存它們。最後,我們在輸出中顯示變數的所有值。
問題在於當使用者輸入 age 的值並按 Enter 鍵時。控制檯應該獲得 firstName 的輸入,但它跳過它並直接進入 lastName。下面的輸出清楚地顯示了問題。
import java.util.Scanner;
public class EnterContinue {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = sc.nextInt();
System.out.print("Enter your First Name: ");
String firstName = sc.nextLine();
System.out.print("Enter your last Name: ");
String lastName = sc.nextLine();
System.out.println("Your Info:\nAge: " + age + "\nFull Name: " + firstName + " " + lastName);
}
}
輸出:
Enter your age: 23
Enter your First Name: Enter your last Name: John
Your Info:
Age: 23
Full Name: John
Process finished with exit code 0
既然我們知道了這個問題,我們就可以討論解決方案以及首先為什麼會出現問題。當我們將 int 值作為輸入時,方法 nextInt() 讀取 int 值並且無法讀取換行符。這就是為什麼當我們在閱讀 int 後按 Enter 時,控制檯會將其視為換行符並將其跳到以下語句。
我們必須在 nextInt() 函式之後使用一個額外的 nextLine() 方法,該方法將跳過換行符並顯示下一行來解決這個問題。在輸出中,我們可以看到現在我們可以輸入名字,這在前面的示例中是不可能的。
import java.util.Scanner;
public class EnterContinue {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = sc.nextInt();
System.out.print("Enter your First Name: ");
String firstName = sc.nextLine();
sc.nextLine();
System.out.print("Enter your last Name: ");
String lastName = sc.nextLine();
System.out.println("Your Info:\nAge: " + age + "\nFull Name: " + firstName + " " + lastName);
}
}
輸出:
Enter your age: 5
Enter your First Name: gfd
Enter your last Name: gfgf
Your Info:
Age: 5
Full Name: gfgf
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
LinkedIn