尝试了以下建议以读取int输入Scanner is skipping nextLine() after using next() or nextFoo()?
无法弄清楚输入不占用换行符的原因。
这是运行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输入的情况下停止循环。
答案 0 :(得分:2)
删除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);