我正在制作一种方法来获取用户想要将多少个数字相加。也就是如果他们想将数字 1 2 和 3 相加。他们想将 3 个数字相加。因此,当我问他们想将多少相加时,我使用 try-catch 来捕捉它们是否输入小数位。因为您不能将 3.5 个数字相加,所以您可以将 3 个数字或 4 个相加。问题是如果用户输入小数,程序将无限循环运行除 try 语句中的内容之外的所有内容。我怎样才能解决这个问题?
这是该方法的代码:
private static int requestMaxInputForFloat(Scanner scanner){
boolean appropriateAnswer = true; // assume appropriate catch not appropriate to loop again
int howManyInputs = 1000000; // hold value to return how many inputs. if this value we will not run.
//request an appropriate number of inputs until appropriate answer = true;
do
{
appropriateAnswer = true; //if looped again reset value to true
try{
System.out.print("How many decimal place numbers would you like to sum? ");
howManyInputs = scanner.nextInt();
}catch(Exception e){
System.out.println("Sorry but you can only request to average a whole number set of data.\nTry Again.");
appropriateAnswer = false;
}//end of try-catch
if (howManyInputs <= 0) //invalid answer
{
System.out.println("Sorry but " + howManyInputs + " is equal to or below 0. Please try again.");
}else{
appropriateAnswer = false;
}
}while(!appropriateAnswer);//end of while loop
return howManyInputs; //return the value
}// end of getMaxInput