[英]how to loop, to ask user input for this Java program?
在这个程序中,一旦捕获到异常,程序就会显示 catch 消息并且程序会自行成功终止(如果要询问用户输入,我需要再次手动运行程序)。 我不希望程序完成,但它应该自动要求用户输入一个有效数字并从头开始执行功能,如何编写?
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Enter a Whole Number to divide: ");
int x = sc.nextInt();
System.out.println("Enter a Whole number to divide by: ");
int y = sc.nextInt();
int z = x / y;
System.out.println("Result is: " + z);
}
catch (Exception e) {
System.out.println("Input a valid number");
}
finally{
sc.close();
}
}
}
Output
Enter a Whole Number to divide:
5
Enter a Whole number to divide by:
a
Input a valid number
Process finished with exit code 0
nextInt
有一些问题需要注意,您可以查看此链接: Scanner is skipping nextLine() after using next() or nextFoo()? .
对于您的程序,请使用 while 循环,并且您需要注意 Y 可能为 0,这将导致ArithmeticException
。
while (true) {
try {
System.out.println("Enter a Whole Number to divide: ");
// use nextLine instead of nextInt
int x = Integer.parseInt(sc.nextLine());
System.out.println("Enter a Whole number to divide by: ");
int y = Integer.parseInt(sc.nextLine());
if (y == 0) {
System.out.println("divisor can not be 0");
continue;
}
double z = ((double) x) / y
System.out.println("Result is: " + z);
break;
}
catch (Exception e) {
System.out.println("Input a valid number");
}
}
sc.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.