我撰寫了這個簡單的回圈來從標準輸入中收集整數。如何修改此回圈,使其在用戶輸入空行時停止?現在回圈繼續進行,忽略空行,它只在我插入一個字母時停止(例如)。
我希望它既可以作為提示,也可以作為標準輸入重定向。
提前致謝。
import java.util.Scanner;
public class example{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
boolean auth = true;
do {
try{
int num = in.nextInt();
in.nextLine();
System.out.println(num);
} catch(Exception e){
System.out.println(e);
in.nextLine();
auth = false;
}
} while(auth);
in.close();
}
}
uj5u.com熱心網友回復:
您可以使用in.nextLine()instead of in.nextInt(),然后使用該isEmpty()函式檢查它是否為空并將Integer.parseInt()其轉換回 int。你可以更有效地做到這一點,但這應該就足夠了
int num = 0;
String input = in.nextLine();
if(input.isEmpty()){
auth = false;
}
else{
num = Integer.parseInt(input);
System.out.println(num);
}
uj5u.com熱心網友回復:
使用 next() 而不是 nextLine()。nextLine() 讀取輸入,包括單詞之間的空格。空格將被讀取為空字串。如果你使用 next(),它根本不會讀取空行。它讀取輸入直到空格。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/414443.html
標籤:
上一篇:十進制值問題
