我将如何在我的程序中打破循环?

时间:2011-10-26 23:57:29

标签: java

public static void date1() {
    int x = 0 ;  //integer for looping

    do // process to follow if length == 5
    {   
        Scanner scanner = new Scanner(System.in);
        try {
            System.out.println("Please enter the first date ");
            System.out.println("Please enter the year: ");
            y1 = scanner.nextInt();

            System.out.println("Please enter the month: ");
            m1 = scanner.nextInt();

            System.out.println("Please enter the day: ");
            d1 = scanner.nextInt();
        } catch (InputMismatchException inputMismatchException) {
            scanner.nextLine();
            System.err.println("You must enter intergers. Please try again. ");
        }
        x = x + 1 ; // set loop to three attempts
    } while (x < 3) ; //do process occurs while attempts are under < 4
}

如果所有输入都正确(输入整数),我想打破循环。我不太确定用什么命令打破我创建的循环。 大家先谢谢大家!

3 个答案:

答案 0 :(得分:3)

在关闭break块之前添加try{}命令。如果没有抛出异常,将执行break命令并退出循环。

然而,更好的方法是创建一个单独的方法,接受来自用户的单个输入,然后调用它三次。这样,如果只有第三个数字无效,则您不必再次输入前两个数字:

private static int getIntInput(){
    while(true){
        try{
            return scanner.nextInt();
        } catch(InputMismatchException e){
            System.out.println("You must enter integers.  Please try again.");
        }
    }
}

public static void date1(){
    int x=0;
    System.out.println("Please enter the first date ");
    System.out.println("Please enter the year: ");
    y1 = getIntInput();
    System.out.println("Please enter the month: ");
    m1 = getIntInput();
    System.out.println("Please enter the day: ");
    d1 = getIntInput();
}

当然,你可以把事情变得更加花哨......我们可以在getIntInput()方法中添加一个String输入,然后在每次接受输入时打印该字符串,这样用户就不会忘记他正试图进入。或者你可以清理语法以便它可以正常工作(我认为编译器会抱怨getIntInput需要返回一个int,就像我现在输入的那样......)

答案 1 :(得分:1)

您可以添加变量boolean stop = false,然后将您的时间修改为while( x < 3 || stop == true)。然后,在您对输入感到满意后,添加一些代码来设置stop = true

答案 2 :(得分:0)

这是一个提示:当所有输入都正确时,“打破”循环。