用try catch和scanner阻止。如何清除扫描仪?

时间:2018-03-14 22:42:13

标签: java

我知道我的代码在"清晰编码"的情况下并不合适。但它只是为了测试一些功能。

所以这里是代码:

int x = 0;
int y = 0;
int index = 0;
boolean flag = true;
Scanner scanner = new Scanner(System.in);

while(flag) {
    try {
        System.out.println("Type the first nubmer: ");
        x = scanner.nextInt();
        scanner.nextLine();
        flag = false;
        break;
    }catch (InputMismatchException e) {
        System.out.println("Type a proper number you idiot!");
        flag = true;
    }

}
flag = true;

while(flag) {
    try {
        System.out.println("Type the second nubmer: ");
        y = scanner.nextInt();
        scanner.nextLine();
        if(y == 0) {
            System.out.println("Can't divide by 0!");
            continue;
        }
        flag = false;
        break;
    }catch (InputMismatchException e) {
        System.out.println("Type a proper number you idiot!");
        flag = true;
    }
}
System.out.println("The result is: " + x/y);

一旦InputMismatchException发生,输出就是无限的:

Type a proper number you idiot!
Type the second nubmer: 
Type a proper number you idiot!

等等。

改善工作的原因是改变

x = scanner.nextInt();
y = scanner.nextInt();

为:

x = Scanner scanner = new Scanner(System.in).nextInt();
y = Scanner scanner = new Scanner(System.in).nextInt();

所以我需要为每个循环创建一个新的Scanner实例。这就是问题 - 如何清除扫描仪以使其工作正常而无需每次都制作新实例?

1 个答案:

答案 0 :(得分:0)

您的问题是,如果用户输入错误,您就没有时间给予输入。第scanner.nextLine()行执行此操作,应该是对代码的修复。如果你有问题,就问吧。

  int x = 0;
    int y = 0;
    int index = 0;
    boolean flag = true;
    Scanner scanner = new Scanner(System.in);

    while(flag) {
        try {
            System.out.println("Type the first nubmer: ");
            x = scanner.nextInt();
            flag = false;
        }catch (Exception e) {
            System.out.println("Type a proper number you idiot!");
            scanner.nextLine();
        }

    }
    flag = true;

    while(flag) {
        try {
            System.out.println("Type the second nubmer: ");
            y = scanner.nextInt();
            if(y == 0) {
                System.out.println("Can't divide by 0!");
                continue;
            }
            flag = false;
        }catch (Exception e) {
            System.out.println("Type a proper number you idiot!");
            scanner.nextLine();
        }
    }
    System.out.println("The result is: " + x/y);