无法允许用户退出

时间:2017-06-03 18:50:04

标签: java

我只是想让用户在输入“Q”时退出程序

但我的程序现在只需将“Q”作为另一个输入并运行程序。这应该是一个仍然致力于辅音簇问题的piglatin翻译器

import java.util.Scanner;

public class Assignment_4_Piglatin {

    public static void main(String[] args) {

        Scanner userWord = new Scanner(System.in);

        System.out.println("K. Caleb Swallow");
        System.out.println("Welcome to the Pig Latin Translator!");

        boolean run = true;
        while (run) {

            System.out.println("Please enter a word(or press Q to quit):");

            String firstLetter = "something";

            String word = userWord.next();


            firstLetter = Character.toString(word.charAt(0));


            if (firstLetter.equals("a") || firstLetter.equals("e") ||
                    firstLetter.equals("i") || firstLetter.equals("o")
                    || firstLetter.equals("u")) {
                System.out.println(word + "way");
            } else {
                System.out.println(word.substring(1) + firstLetter + "ay");
            }

            if (word.equals("Q")) {
                System.exit(0);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

立即尝试运行此功能。在if-else语句中稍作修改。

import java.util.Scanner;
public class Assignment_4_Piglatin {
    public static void main(String[] args) {

        Scanner userWord = new Scanner(System.in);
        System.out.println("K. Caleb Swallow");
        System.out.println("Welcome to the Pig Latin Translator!");

        boolean run = true;
        while (run) {

            System.out.println("Please enter a word(or press Q to quit):");
            String firstLetter = "something";
            String word = userWord.next();

            firstLetter = Character.toString(word.charAt(0));

            if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o")
                || firstLetter.equals("u")) {
                System.out.println(word + "way");
            } else if (word.equals("Q")) {
                System.exit(0);
            } else {
                System.out.println(word.substring(1) + firstLetter + "ay");
            }
        }
        userWord.close();
    }
}

答案 1 :(得分:0)

根据我的理解,你只想在用户提供'Q'或'q'时停止执行,这样就可以阻止JVM运行你的应用程序。试试这个。

if(firstLetter.equals("Q") || firstLetter.equals("q")){
    System.exit(0);//static method for stopping the JVM from System class
}