【问题标题】:how to loop, to ask user input for this Java program?如何循环,询问用户对该 Java 程序的输入?
【发布时间】:2021-11-22 04:24:44
【问题描述】:

在这个程序中,一旦捕获到异常,程序就会显示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();
        }
    }
}

输出

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

【问题讨论】:

    标签: java loops exception


    【解决方案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();
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    相关资源
    最近更新 更多