在嘗試這些讀取 int 輸入的建議后,掃描儀在使用 next() 或 nextFoo() 之后跳過 nextLine() 嗎?無法弄清楚輸入為什么不消耗換行符。這是運行jdk 11的linux。import java.util.Scanner;public class NumbFile {? ? public static void main(String[] args) throws Exception {? ? ? ? int i = 100;? ? ? ? int powerNumber;? ? ? ? boolean status = true;? ? ? ? ? ? do {? ? ? ? ? ? ? ? try {? ? ? ? ? ? ? ? ? ? System.out.print("Type a number: ");? ? ? ? ? ? ? ? ? ? Scanner sc = new Scanner(System.in);? ? ? ? ? ? ? ? ? ? powerNumber = Integer.parseInt(sc.nextLine());? ? ? ? ? ? ? ? ? ? System.out.println(i * powerNumber);? ? ? ? ? ? ? ? ? ? sc.close();? ? ? ? ? ? ? ? } catch (NumberFormatException exc) {? ? ? ? ? ? ? ? ? ? exc.printStackTrace();? ? ? ? ? ? ? ? ? ? status = false;? ? ? ? ? ? ? ? }? ? ? ? ? ? } while(status);? ? }}這應該僅在沒有 int 輸入的情況下停止循環。
1 回答

暮色呼如
TA貢獻1853條經驗 獲得超9個贊
刪除sc.close();. 這會關閉你的Scanner(應該在循環之前聲明一次),但它也會關閉System.in(你不能重新打開它)。
int i = 100;
boolean status = true;
Scanner sc = new Scanner(System.in);
do {
try {
System.out.print("Type a number: ");
int powerNumber = Integer.parseInt(sc.nextLine());
System.out.println(i * powerNumber);
} catch (NumberFormatException exc) {
exc.printStackTrace();
status = false;
}
} while (status);
添加回答
舉報
0/150
提交
取消