1

在学校,我正在创建一个简单的几何程序,询问形状的角数和坐标。为了防止错误的输入(即字符而不是整数),我想我会使用异常处理。它似乎工作正常,但是一旦我输入错误,它就会捕获错误并设置一些默认值。它应该继续要求更多输入,但不知何故,这些最终会在不要求新输入的情况下捕获相同的异常。

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

    try {
        int hoeken;
        System.out.print("How many corners does your shape have? ");

        try {
            hoeken = stdin.nextInt();
            if(hoeken < 3) throw new InputMismatchException("Invalid side count.");
        }
        catch(InputMismatchException eVlakken){
            System.out.println("Wrong input. Triangle is being created");
            hoeken = 3;
        }

        Veelhoek vh = new Veelhoek(hoeken);
        int x = 0, y = 0;

        System.out.println("Input the coordinates of your shape.");
        for(int i = 0; i < hoeken; i++){
            System.out.println("Corner "+(i+1));                
            try {
                System.out.print("X: ");
                x = stdin.nextInt();
                System.out.print("Y: ");
                y = stdin.nextInt();                    
            } catch(InputMismatchException eHoek){
                x = 0;
                y = 0;
                System.out.println("Wrong input. Autoset coordinates to 0, 0");
            }                
            vh.setPunt(i, new Punt(x, y));
        }

        vh.print();

        System.out.println("How may points does your shape needs to be shifted?");
        try {
            System.out.print("X: ");
            x = stdin.nextInt();
            System.out.print("Y: ");
            y = stdin.nextInt();

        } catch(InputMismatchException eShift){
            System.out.println("Wrong input. Shape is being shifted by 5 points each direction.");
            x = 5;
            y = 5;
        }            

        vh.verschuif(x, y);
        vh.print();

    } catch(Exception e){
        System.out.println("Unknown error occurred. "+e.toString());
    } 
}

因此,如果用户开始尝试创建具有 2 个边的形状或输入 char 而不是整数,它会产生 InputMismatchException 并处理它。然后它应该通过询问角的坐标来继续程序,但它会不断抛出新的异常并且句柄会这样做。

出了什么问题?

4

1 回答 1

2

According I the API you need to skip the error ous entry to get the next one . "When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method."

Calling the skip() method after getting the exception should fix this. http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

于 2012-10-07T08:56:50.203 回答