在Java中发生异常后重新提示

时间:2015-12-03 06:42:46

标签: java exception

我记得在Python中遇到过这个问题。这个Java代码是我的Python代码的副本,它计算三角形的面积。如果输入了非数字值,我会遇到异常,但最终结果会变得很糟糕。

private static float baseLength() {
    float baseLength = 0;
    Scanner user_input = new Scanner(System.in);
    try {
        while (baseLength <= 0) {
            System.out.print("Enter the base length of the triangle: ");
            baseLength = user_input.nextFloat();
            if (baseLength <=0) {
                System.out.println("Error. Plase enter a number higher than 0.");
            }
        }            
    } catch (InputMismatchException badChar) {   
        System.err.println("You have entered a bad value. Please try again");
        baseLength();
    }
    return baseLength;

它将从错误的数字中恢复,但不会从不是数字的值中恢复。我仍然无法弄清楚具体问题是什么。

2 个答案:

答案 0 :(得分:1)

您可以在try / catch块周围放置 <activity android:name=".MyActivity" android:windowSoftInputMode="adjustPan"> </activity> 循环来实现此目的:

while

答案 1 :(得分:0)

测试更清晰,主循环内部异常,以及System.err的每个错误

private static float baseLength() {
   float baseLength = 0;

   while (true)
   {
   try {
       System.out.print("Enter the base length of the triangle: ");

        Scanner user_input = new Scanner(System.in);
        baseLength = user_input.nextFloat();

        if (baseLength>0)
           return baseLength;

        if (baseLength <=0)
               System.err.println("Error. Plase enter a number higher than 0.");
       } 
       catch (InputMismatchException badChar)
       {   
       System.err.println("You have entered a bad value. Please try again");
       }
   }
 }