← 從零開始學 Java
第 47 課,共 88 課 · 10 XP
使用者的輸入
理論與題目說明
機器翻譯,尚未經母語人士審閱。
Scanner 以詞(記號)或行為單位讀取輸入:
Scanner in = new Scanner(System.in);
int age = in.nextInt(); // 詞 → int
double h = in.nextDouble();
String word = in.next(); // 一個詞
String line = in.nextLine(); // 目前這一行剩下的全部
boolean more = in.hasNextInt(); // 下一個是不是整數——不會讀取
新手的頭號陷阱: nextInt() 之後換行還沒被讀走,所以接下來的 nextLine() 會回傳
空字串:
int n = in.nextInt(); // 輸入 "25⏎Alex Kai⏎"
String name = in.nextLine(); // ""——讀到的是 25 那一行剩下的部分!
in.nextLine(); // 解決方法:用另一次呼叫把這一行剩下的部分「吃掉」
「型別不對」的輸入(用 abc 代替數字)會拋出 InputMismatchException。
題目。 輸入:全名一行、年齡一行、身高(實數)一行、興趣一行
(可能有好幾個詞)。輸出 名字: …、5 年後: …、身高: … m(小數點後 2 位)、興趣: …。