结束这个do-while循环?

时间:2011-06-08 09:53:58

标签: java do-while

当用户输入0时,如何结束do-while循环?

如果用户输入F,G,H和J,程序将继续执行。 如果用户输入0,程序将退出。

import java.util.Scanner;

public class P4Q5 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {


        Scanner sc = new Scanner(System.in);
        System.out.println("\nMain Menu: \n" +
                "Enter 0 to exit program\n" +
                "Enter F to display Faith\n" +
                "Enter G to display Grace\n" +
                "Enter H to display Hope\n" +
                "Enter J to display Joy\n");



        do {
             System.out.print("Enter your choice:");
               String s = sc.nextLine();
            char ch = s.charAt(0);
            if (( ch == 'F'))  {
                System.out.println("\nFaith\n");
            }

            else if  (( ch == 'G')) {
                System.out.println("\nGrace\n");
            }

            else if  (( ch == 'H')) {
                System.out.println("\nHope\n");
            }

            else if  (( ch == 'J')) {
                System.out.println("\nJoy\n");
            }



            else  {
                System.out.println("\nWrong option entered!!\n");
            }

        } while (ch == 'O');

              // TODO code application logic here
    }

}

4 个答案:

答案 0 :(得分:2)

while (ch != '0')而不是while (ch == 'O')怎么样?请注意0O之间的区别?

答案 1 :(得分:1)

在你做的时候尝试这个:

if( ch == '0') break;

答案 2 :(得分:1)

试试这个:

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("\nMain Menu: \n" +
        "Enter 0 to exit program\n" +
        "Enter F to display Faith\n" +
        "Enter G to display Grace\n" +
        "Enter H to display Hope\n" +
        "Enter J to display Joy\n");



do {
     System.out.print("Enter your choice:");
       String s = sc.nextLine();
    char ch = s.charAt(0);
    if (( ch == 'F'))  {
        System.out.println("\nFaith\n");
    }

    else if  (( ch == 'G')) {
        System.out.println("\nGrace\n");
    }

    else if  (( ch == 'H')) {
        System.out.println("\nHope\n");
    }

    else if  (( ch == 'J')) {
        System.out.println("\nJoy\n");
    }

    else if (( ch == 'O' )) {
        System.exit();
    }

    else  {
        System.out.println("\nWrong option entered!!\n");
    }

} while (ch == 'F' || ch == 'G' || ch == 'H' || ch == 'J' || ch == 'O');

      // TODO code application logic here

}

要退出程序,您需要执行System.exit()

要退出循环,请执行@bitmask声明

答案 3 :(得分:0)

我会使用布尔变量,如果输入0则布尔值变为true,然后检查布尔值...

    boolean bool = false;
    do {
         ...

        if(input == '0')
           bool=true;
    } while (!bool);
哦,在我忘记之前,我还会在do while之前做一个输入,在循环结束之前做一个输入。就像那样,你点击0后你的整个代码都不会再运行。

相关问题