java - 为什么在我的 java 程序中没有正确处理这个异常?

标签 java exception methods

这个程序的目标是找到用户输入的具有 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.");

    }    } 
    }
    }

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

最佳答案

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

java.util.InputMismatchException

此外,您可以调用

,而不是等待异常
hasNextInt()

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

关于java - 为什么在我的 java 程序中没有正确处理这个异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34160879/

相关文章:

java - 我的代码中出现错误如何修复?

c# 字典方法作为一个值

java - 一个正则表达式,用于捕获两个略有不同的模式

java - java中的类和接口(interface)初始化

java - 在 Java 8 中,如果映射具有重复值,则获取重复值异常

java - 如果未选择,则在 UI 中显示带有默认值的枚举值

android - 如何在出现任何异常时暂停 Eclipse?

java - 正确使用Java异常

java - 在测试中模拟 CompletionException

java - 第一次使用数组,尝试创建频率表