【问题标题】:try statement not being used on second illiteration of loop [duplicate]循环第二次文盲时未使用尝试语句[重复]
【发布时间】: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


【解决方案1】:

在 catch 块中添加 scanner.nextLine();。我认为问题在于,如果nextInt() 出错,扫描仪的“指针”仍然指向错误字符,如果您再次尝试nextInt(),它将尝试再次扫描相同的错误字符。你必须做一些事情让扫描仪跳过它。在这里,您只想丢弃用户输入的任何内容,因此最合适的是 nextLine(),它会跳过输入行的整个剩余部分。

另一件事:我会改变

if (howManyInputs <= 0) //invalid answer

if (appropriateAnswer && howManyInputs <= 0) //invalid answer

否则,如果用户输入-1,则循环将返回,howManyInputs 仍将是-1;那么如果用户键入 3.5,您将收到异常,但您会收到第二条错误消息,因为 howManyInputs 仍然是前一个循环剩余的 -1。如果您已经知道存在输入错误,则无需测试 howManyInputs

【讨论】:

  • 是的,这行得通,而且您对您建议的更改是正确的。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2016-12-02
  • 2012-02-25
  • 2020-07-18
  • 1970-01-01
  • 1970-01-01
  • 2012-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多