我是新来的Java,我想继续询问用户输入,直到用户输入一个整数,这样就没有InputMismatchException。我试过这段代码,但是当我输入一个非整数值时,我仍然会得到异常。如何循环用户输入,直到输入整数?
int getInt(String prompt){
System.out.print(prompt);
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt()){
System.out.println("Enter a whole number.");
sc.nextInt();
}
return sc.nextInt();
}
谢谢你的时间!
感谢您的帮助,快乐编码 –