简体   繁体   English

如何循环,询问用户输入这个 Java 程序?

[英]how to loop, to ask user input for this Java program?

at this program once the exception is caught, the program displays the catch message and program terminates successfully by itself (I need to run the program again manually if want to ask the user input).在这个程序中,一旦捕获到异常,程序就会显示 catch 消息并且程序会自行成功终止(如果要询问用户输入,我需要再次手动运行程序)。 I dont want the program to finish but automatically it should ask the user to enter a valid number and performs the functions from the beginning, how to write for this?我不希望程序完成,但它应该自动要求用户输入一个有效数字并从头开始执行功能,如何编写?

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 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

There are some issues with nextInt that you need to be careful about, You can check out this link: Scanner is skipping nextLine() after using next() or nextFoo()? nextInt有一些问题需要注意,您可以查看此链接: Scanner is skipping nextLine() after using next() or nextFoo()? . .

For your program, use a while loop, and you need to be aware of Y could be 0, which would cause an ArithmeticException .对于您的程序,请使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM