有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何循环,请求用户输入这个Java程序?

在这个程序中,一旦捕捉到异常,程序就会显示捕捉消息,程序会自动成功终止(如果想询问用户输入,我需要再次手动运行程序)。我不希望程序完成,但它会自动要求用户输入一个有效的数字,并从一开始就执行功能,如何为此编写

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();
        }
    }
}

输出

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

共 (1) 个答案

  1. # 1 楼答案

    有一些关于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();