如果用户输入“N'”,如何让我的程序退出?

时间:2016-01-21 21:17:07

标签: java

如果用户输入“N'”,如何退出程序?

Scanner scan = new Scanner(System.in);
System.out.println("Would you like to buy and dairy products? Y/N ");
String answer = scan.nextLine();

switch (answer)
{
case "Y":
case "y":
    System.out.println("\nHere are our list of dairy products:-");
    break;
case "N":
case "n"://exit from program;
    System.out.println("You don't want any dairy items");
    break;
default :
    System.out.println("Invalid choice, please select Yes/No bu entering the characters 'Y'/'N'");
    break;
}

2 个答案:

答案 0 :(得分:4)

假设这是在main方法中,你可以使用assign_sub语句,它结束方法,从而结束程序。

否则return;将起作用。

答案 1 :(得分:0)

稍微好一点的做法......你做的是什么:

Scanner scan = new Scanner(System.in);

System.out.println("Would you like to buy any dairy products? Y/N ");
String answer = "";

while (!answer.equals("y") && !answer.equals("n")) {
    answer = scan.nextLine().toLowerCase();

    switch (answer) {
        case "y":
            System.out.println("\nHere are our list of dairy products:-");
            break;
        case "n"://exit from program;
            System.out.println("You don't want any dairy items");
            System.exit(0); // program terminates if N or n was supplied.
            break;
        default :
            System.out.println("Invalid choice, please select Yes/No by entering the characters Y or N");
            break;
    }
}
// Code continues here if Y or y was supplied.