Вам нужно что-то вроде:
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);
}
}
}
}