编写一个程序,该程序将给使用提示输入两个double值

时间:2018-11-14 13:43:17

标签: java

教授要求我们编写一个程序,该程序将向用户提示输入两个浮点(或双精度)值。如果输入的值正确,则显示输入的两个值。如果用户输入字符而不是数字,或者输入的数字无效,则程序将显示错误消息,并要求用户再次输入正确的值。仅在收到并显示正确的输入后退出。

但是,我编写了一个程序,该程序仅在用户输入两个正确的双精度数时才起作用。有人可以帮我改变捕捉错误的路线吗?谢谢。

import java.util.Scanner;

public class FiveSecond {

    static void printMenu() {
        System.out.println("Welcome to get two doubles program:");
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        boolean valid = false;
        double first = 0;
        double second = 0;

        printMenu();

        while(!valid) {
            System.out.print("Enter two doubles, seperate by space ");

            try {
                first = Double.parseDouble(scan.next());
                second = Double.parseDouble(scan.next());
            } catch (NumberFormatException e) {
                System.out.println("Try again");
            }

            valid = true;   
        }

        System.out.println("You entered valid choice: " + first + " " +second);
        System.out.println("Thank you for giving your choice.");

        scan.close();
    }

}

2 个答案:

答案 0 :(得分:0)

除了前面的注释之外,您还必须小心,因为如果您不重置扫描仪,扫描仪将“记住”先前正确的记录:

已编辑:感谢@Stultuske评论

while (!valid) {
    System.out.print("Enter two doubles, seperate by space ");
    try {
        first = Double.parseDouble(scan.next());
        second = Double.parseDouble(scan.next());
        valid = true;
    }
    catch (NumberFormatException e) {
        System.out.println("Try again");
        scan.nextLine(); // <------- Important line
    }
}

答案 1 :(得分:0)

尝试一下:

catch (NumberFormatException e) {
           System.out.println("Try again");
           continue;
       }