繁体   English   中英

为什么在我的Java程序中不能正确处理此异常?

[英]Why isnt this Exception handling correctly in my java program?

该程序的目标是找到用户键入的带有4个点的圆的区域,如果用户键入的不是整数,我希望输出消息(“仅数字”)

package areacircleexception;
import java.util.Scanner;

public class AreaCircleException {
    public static double distance
           (double x1, double y1, double x2, double y2)
{
    double dx = x2 - x1;
    double dy = y2 - y1;
    double dsquared = dx*dx + dy*dy;
    double result = Math.sqrt (dsquared);
    return result;
}

public static double areaCircle(double x1, double y1, double x2, double y2)
{
    double secretSauce = distance(x1, y1, x2, y2);
    return areaCircleOG(secretSauce);
}

public static double areaCircleOG(double secretSauce)
{

    double area = Math.PI * Math.pow(secretSauce, 2);
    return area;
}

我认为我的问题与下面的这种方法有关。

    public static int getScannerInt (String promptStr){
    Scanner reader = new Scanner (System.in);
    System.out.print ("Type The x1 point please: ");
        int x1 = reader.nextInt();  
        return 0;

}
public static void main(String[] args) 
{
Scanner reader = new Scanner (System.in);

boolean getScannerInt = false;
while(!getScannerInt)
{
    try
    {
        System.out.print ("Type The x1 point please: ");
        int x1 = reader.nextInt();
        System.out.print ("Type The x2 point please: ");
        int x2 = reader.nextInt();
        System.out.print ("Type The y1 point please: ");
        int y1 = reader.nextInt();
        System.out.print ("Type the y2 point please: ");
        int y2 = reader.nextInt();
        double area = areaCircle(x1, x2, y1, y2);
        System.out.println ("The area of your circle is: " + area);
        getScannerInt = true;

    }
    catch(NumberFormatException e)
    {
        System.out.println("Please type in a number! Try again.");

    }    } 
    }
    }

除了异常以外,程序可以正常工作,但是当我键入字符串时,它无法处理我的异常,因此我无法弄清原因。

您没有抓住正确的Exception 这就是为什么你从来没有进入catch当你输入一个String 使用字符串会引发InputMismatchException而不是NumberFormatException 您可以通过执行以下操作来更改catch语句以捕获所有Exception

catch(Exception e){...} 

编辑:即使进行了上述更改,您也可能陷入无限循环。 要解决此问题,您需要在进入catch块的while循环的每次迭代中都到达行尾。 将您的catch块更改为此,您应该会很好:

catch(Exception e){
    System.out.println("Please type in a number! Try again.");
    reader.nextLine();
} 

当您调用nextInt且您的下一个输入不是有效的整数时,您得到的异常是:

java.util.InputMismatchException

另外,您可以致电,而不是等待异常

hasNextInt()

如果下一个传入令牌是整数,则此方法返回true,否则返回false。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM