为什么我的java程序不能正确处理这个异常?
该程序的目标是找到用户键入的具有4个点的圆的面积,如果用户键入的不是整数,则我希望消息仅输出数字为什么我的java程序不能正确处理这个异常?,java,exception,methods,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
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.");
} }
}
}
除了异常之外,程序工作正常,但当我键入字符串时,它不会处理我的异常,我无法找出原因。您捕获的异常不正确。这就是为什么当你输入一个字符串时,你永远不会进入捕捉。使用字符串会引发InputMismatchException,而不是NumberFormatException。通过执行以下操作,可以更改catch语句以捕获所有异常:
catch(Exception e){...}
编辑:即使进行了上述更改,您也可能最终陷入无限循环。要解决这个问题,您需要在进入catch块的while循环的每次迭代中到达行的末尾。将您的挡块更改为此,您应该表现良好:
catch(Exception e){
System.out.println("Please type in a number! Try again.");
reader.nextLine();
}
您没有捕获正确的异常。这就是为什么当你输入一个字符串时,你永远不会进入捕捉。使用字符串会引发InputMismatchException,而不是NumberFormatException。通过执行以下操作,可以更改catch语句以捕获所有异常:
catch(Exception e){...}
编辑:即使进行了上述更改,您也可能最终陷入无限循环。要解决这个问题,您需要在进入catch块的while循环的每次迭代中到达行的末尾。将您的挡块更改为此,您应该表现良好:
catch(Exception e){
System.out.println("Please type in a number! Try again.");
reader.nextLine();
}
当您调用nextInt,并且下一个输入不是有效的整数时,您得到的异常是:
java.util.InputMismatchException
此外,您可以调用
hasNextInt()
如果下一个传入令牌是整数,则此方法返回true,否则返回false。当您调用nextInt,并且下一个输入不是有效整数时,您得到的异常是:
java.util.InputMismatchException
此外,您可以调用
hasNextInt()
如果下一个传入令牌是整数,则此方法返回true,否则返回false。扫描程序可以引发其他异常扫描程序可以引发其他异常不捕获异常类。您应该捕获每个块中的具体异常。对于基本用户输入?我不同意。只要知道抛出的异常类型,捕获所有异常并没有什么错。不要捕获异常类。您应该捕获每个块中的具体异常。对于基本用户输入?我不同意。只要知道抛出的异常类型,捕获所有异常没有什么错。