对于大学评估,我必须使用名为sc的Scanner和类级作用域,并且整个程序必须包含在一个类中。 main方法调用menu()
方法,该方法使用Scanner和for循环调用两种方法之一来响应用户输入。
这两种方法中的一种使用扫描仪来计算输入整数的阶乘。执行该方法后,menu()
中的for循环继续。为了避免由于用户输入浮点数而导致的InputMismatchException,我使用了try / catch。但是,当程序返回menu()
for循环时,扫描程序在分配给choice
时会导致InputMismatchException。如何让Scanner再次提示用户输入?抱歉,如果我遗漏了一些明显的东西,这是我学过的第一种编程语言。这应该是精简的可编译代码:
package summativeassessment;
import java.util.InputMismatchException;
import java.util.Scanner;
public class SummativeAssessment {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
menu();
}
public static void menu(){
String fName;
String sName;
System.out.print("Enter your first name: ");
fName = sc.next();
System.out.print("Enter your last name: ");
sName = sc.next();
try{
for(int choice = 1; choice!=0;){
System.out.print("Option 1 to generate username. Option 2 to calculate factorial. Press 0 to quit: ");
choice = sc.nextInt();
switch(choice){
case 2:
System.out.println(fName+" "+sName+", you have selected option 2");
numberFactorial();
break;
case 0:
break;
default:
System.out.println("Invalid option. Please try again.");
}
}
} catch(InputMismatchException ex){
String msg = ex.getMessage();
System.out.println(msg);
}
}
public static void numberFactorial(){
System.out.print("Enter a number: ");
try{
int numIn = sc.nextInt();
long result = numIn;
if(numIn>0){
for(int factor = 1; factor<numIn; factor++){
result *= factor;
if(factor==numIn-1){
System.out.println("The factorial is "+result);
}
}
}
else{
System.out.println("Enter a positive integer greater than 0");
}
}
catch(InputMismatchException ex){
System.out.println("Input invalid");
}
}
}
答案 0 :(得分:0)
我调试了你的代码并得到了这个结果:
如果输入float作为输入,则会触发InputMismatchException,但缓冲区中仍有一些内容。所以下次调用sc.nextInt()时,它不会等到你输入一个值,因为某些东西已经存在于缓冲区中,所以它从缓冲区中获取下一个值并尝试解释为整数。但是,它没有这样做,因为它不是一个整数,所以会再次引发InputMismatchException并将其捕获到菜单的catch中,现在导致程序退出。
解决方案是在第一次引发异常后绘制缓冲区中剩余的内容。
因此,工作代码将在异常中包含缓冲区清除sc.next():
public static void numberFactorial(){
System.out.print("Enter a number: ");
try{
int numIn = sc.nextInt();
long result = numIn;
if(numIn>0){
for(int factor = 1; factor<numIn; factor++){
result *= factor;
if(factor==numIn-1){
System.out.println("The factorial is "+result);
}
}
}
else{
System.out.println("Enter a positive integer greater than 0");
}
}
catch(InputMismatchException ex){
System.out.println("Input invalid");
sc.next();
}
}