Как я могу решить проблему бесконечности, используя блоки try-catch? - PullRequest
0 голосов
/ 29 октября 2019

Я пытаюсь отладить мою программу, где она может перехватить все ошибки за пределами целочисленного значения и создать отчет с помощью try-catch. Когда я ввожу строку, я получаю бесконечный цикл и не могу понять, как ее остановить.

import java.util.Scanner;
import java.lang.ArithmeticException;
import java.util.InputMismatchException;

public class Divide {
    public static void main(String[] args) {

        int num1 = 0;
        int num2 = 0;
        double ratio;
        Scanner scan = new Scanner(System.in);
        int x = 1; // using variable for do-while loop

        do { // re-runs code if input error
            try {
                System.out.println("Let's divide some numbers!");
                System.out.print("Enter your first number: ");
                num1 = scan.nextInt();
                System.out.print("Enter your second number: ");
                num2 = scan.nextInt();
                ratio = ((double) num1 / num2);
                System.out.println("Eureka!  the answer is " + ratio);
                x = 2;
            } catch (ArithmeticException e) {
                System.out.println("No division by zero!");
            } catch (Exception e) {
                System.out.println("This won't work. Try again.");
            }

        } while (x == 1);
    }
}

Вывод: Давайте разделим несколько чисел! Введите ваше первое целое число: Y Неправильный ввод: nullLet делит несколько чисел! Введите первое целое число: Неправильный ввод: nullLet делит несколько чисел! Введите ваше первое целое число: Неправильный ввод: nullLet делит несколько чисел!

1 Ответ

2 голосов
/ 29 октября 2019

Вам нужно что-то вроде:

import java.util.Scanner;

public class Divide {
    public static void main(String[] args) {

        int num1 = 0;
        int num2 = 0;
        double ratio;
        Scanner scan = new Scanner(System.in);
        int x = 1; // using variable for do-while loop

        do { // re-runs code if input error
            try {
                System.out.println("Let's divide some numbers!");
                System.out.print("Enter your first number: ");
                num1 = scan.nextInt();
                System.out.print("Enter your second number: ");
                num2 = scan.nextInt();
                if (num2 != 0) {
                    ratio = ((double) num1 / num2);
                    System.out.println("Eureka!  the answer is " + ratio);
                } else {
                    System.out.println("The second number should not be 0");
                }
            } catch (Exception e) {
                System.out.println("This won't work. Try again.");
                x = 2;
            }
        } while (x == 1);
    }
}

Пример прогона:

Let's divide some numbers!
Enter your first number: 10
Enter your second number: 5
Eureka!  the answer is 2.0
Let's divide some numbers!
Enter your first number: 12
Enter your second number: 0
The second number should not be 0
Let's divide some numbers!
Enter your first number: 23
Enter your second number: 5
Eureka!  the answer is 4.6
Let's divide some numbers!
Enter your first number: 50
Enter your second number: abc
This won't work. Try again.

Программа остановит выполнение в этот момент.

Обновление: Я только что увидел ваш комментарий, что вы не хотите, чтобы ваша программа остановилась даже при неправильном вводе (например, abc). Для этого все, что вам нужно сделать, это снова создать экземпляр объекта Scanner. Ниже приведена полная программа с примером выполнения:

import java.util.Scanner;

public class Divide {
    public static void main(String[] args) {

        int num1 = 0;
        int num2 = 0;
        double ratio;
        Scanner scan = new Scanner(System.in);
        int x = 1; // using variable for do-while loop

        do { // re-runs code if input error
            try {
                System.out.println("Let's divide some numbers!");
                System.out.print("Enter your first number: ");
                num1 = scan.nextInt();
                System.out.print("Enter your second number: ");
                num2 = scan.nextInt();
                if (num2 != 0) {
                    ratio = ((double) num1 / num2);
                    System.out.println("Eureka!  the answer is " + ratio);
                } else {
                    System.out.println("The second number should not be 0");
                }
            } catch (Exception e) {
                System.out.println("This won't work. Try again.");
                scan = new Scanner(System.in);
            }
        } while (x == 1);
    }
}

Пример выполнения:

Let's divide some numbers!
Enter your first number: 10
Enter your second number: 5
Eureka!  the answer is 2.0
Let's divide some numbers!
Enter your first number: 10
Enter your second number: 0
The second number should not be 0
Let's divide some numbers!
Enter your first number: 10
Enter your second number: abc
This won't work. Try again.
Let's divide some numbers!
Enter your first number: 10
Enter your second number: 5
Eureka!  the answer is 2.0
Let's divide some numbers!
Enter your first number: 

Надеюсь, это удовлетворяет вашим требованиям. Не стесняйтесь, дайте мне знать, если вам нужно что-то еще.

Теперь вы можете даже удалить избыточную переменную x следующим образом:

import java.util.Scanner;

public class Divide {
    public static void main(String[] args) {

        int num1 = 0;
        int num2 = 0;
        double ratio;
        Scanner scan = new Scanner(System.in);

        while (true) { 
            try {
                System.out.println("Let's divide some numbers!");
                System.out.print("Enter your first number: ");
                num1 = scan.nextInt();
                System.out.print("Enter your second number: ");
                num2 = scan.nextInt();
                if (num2 != 0) {
                    ratio = ((double) num1 / num2);
                    System.out.println("Eureka!  the answer is " + ratio);
                } else {
                    System.out.println("The second number should not be 0");
                }
            } catch (Exception e) {
                System.out.println("This won't work. Try again.");
                // re-runs code if input error
                scan = new Scanner(System.in);
            }
        }
    }
}
...