【发布时间】:2013-09-11 01:42:58
【问题描述】:
我正在制作一种方法来获取用户想要将多少个数字相加。也就是如果他们想将数字 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
【问题讨论】:
-
在
scanner.nextInt()之后添加一个新行并再次运行。 -
我仍然陷入无限循环。即使在 nextInt() 之后有新行;我现在注意到它正在运行 Try 循环并打印 print();但它好像跳过了 .nextInt();部分。
-
在
catch块中尝试scanner.nextLine()。我认为问题在于,如果nextInt()出错,扫描仪的“指针”仍然指向错误字符(如小数点),如果您再次尝试nextInt(),它将尝试扫描相同坏性格又来了。你必须做一些事情让扫描仪跳过它。 -
感谢 Ajb!解决了它。感谢您的帮助。
-
好的,我会把它作为答案发布...
标签: java try-catch infinite-loop do-while