首页 > 解决方案 > 在输入有效之前如何要求用户输入?

问题描述

我想让用户输入两个代表三角形边的双精度数,然后计算斜边。首先,用户指定他们想要的命令(A、B、C 或 Q),然后对于 A 和 B(侧面输入),要求他们输入双精度。现在,当他们没有输入双精度时,程序会要求他们输入第一个输入(A、B、C、Q)。我希望程序只要求他们再做一次,直到输入有效。

我的代码如下:

import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {

    Double sideA = null;
    Double sideB = null;
    Scanner scanner = new Scanner(System.in);


    while (true) {

        System.out.println("Enter command: ");
        String command = scanner.nextLine();

        try {   // checks command, throws exception if not A, B, C or Q
            if (command.equals("A")) {
                System.out.println("Enter a value for side A:");
                sideA = scanner.nextDouble();                       // throws InputMismatchException if not a double
                scanner.nextLine();
                try {
                    if (sideA < 0 || sideA == 0.0) {
                        throw new InputMismatchException();
                    }
                } catch (InputMismatchException e) {
                    System.out.println("Value is invalid. Must be positve and a double.");
                }

            }
            else if (command.equals("B")) {
                System.out.println("Enter a value for side B:");
                sideB = scanner.nextDouble();                       // throws InputMismatchException if not a double
                scanner.nextLine();

                try {
                    if (sideB < 0 || sideB == 0.0) {
                        throw new InputMismatchException();
                    }
                } catch (InputMismatchException e) {
                    System.out.println("Value is invalid. Must be positive and a double.");
                }

            }
            else if (command.equals("C")) {
                Triangle calculate = new Triangle(sideA, sideB);
                System.out.println(calculate.calcHypotenuse());
                break;
            }
            else if (command.equals("Q")) {
                System.exit(0);
            }
            else {
                throw new IllegalArgumentException();
            }

        } 
        catch (IllegalArgumentException e) {
            System.out.println("Command is invalid, Enter A, B, C, or Q.");
        }
        catch (InputMismatchException e) {
            System.out.println("Value is invalid. Must be positve and a double.");
            scanner.nextLine();
        }

    }
}   

}

标签: javaexceptionexception-handlingconditional

解决方案


快速查看您的代码,您只需将命令字符串移到 while 循环之外即可实现您想要的

String command = null;
while (true) {

    if (command == null) {
        System.out.println("Enter command: ");
        command = scanner.nextLine();
    }
    ....

}

还要考虑合并try-catch代码,以免重复代码


推荐阅读