如何用用户输入的字符串结束do while循环?

时间:2015-03-09 14:58:47

标签: java

public static void main (String[] args)
    {
        do {
            Scanner keyboard = new Scanner(System.in);
            System.out.print("Enter a string: ");
            String sentence = keyboard.nextLine();

            System.out.print("Enter a letter: ");
            String fullLetter = keyboard.nextLine();
            char letter = fullLetter.charAt(0);
            keyboard.nextLine();

            int amount = 0;
            for (int i = 0; i < sentence.length(); i++) {
                char ch = sentence.charAt(i);
                if (ch == letter) {
                    amount++;
                }
            }

            System.out.println(letter + " appears " + amount + " times in " + sentence);

            System.out.print("Continue? ");
            String decide = keyboard.nextLine();
        } while (decide.equals("yes"));
    }

}

我希望用户在循环结束时输入“是”或“否”,然后我希望该输入确定程序是否会再次循环。就目前而言,我的代码的最后一行不起作用。我环顾四周,我不知道该怎么做才能解决这个问题。

4 个答案:

答案 0 :(得分:4)

您需要在循环外声明变量decide并在内部初始化:

String decide;
do {
    //do something ...
    decide = keyboard.nextLine();
} while (decide.equals("yes"));

答案 1 :(得分:0)

您应该使用keyboard.next()来阅读String而不是keyboard.nextLine()

next()只读一个单词,nextLine()读取整行,包括Enter,这样就永远不会等于&#34;是&#34;

答案 2 :(得分:0)

您必须声明在do / while循环之外声明字符串describe,否则它是do / while循环的局部变量,并且do测试部分无法访问它。只需使用

public static void main(String[] args) {
String decide;
        do {
            Scanner keyboard = new Scanner(System.in);
            System.out.print("Enter a string: ");
            String sentence = keyboard.nextLine();

            System.out.print("Enter a letter: ");
            String fullLetter = keyboard.nextLine();
            char letter = fullLetter.charAt(0);
            keyboard.nextLine();

            int amount = 0;
            for (int i = 0; i < sentence.length(); i++) {
                char ch = sentence.charAt(i);
                if (ch == letter) {
                    amount++;
                }
            }

            System.out.println(letter + " appears " + amount + " times in "
                    + sentence);

            System.out.print("Continue? ");
            decide = keyboard.nextLine();
        } while (decide.equals("yes"));
    }

将解决您的问题。

答案 3 :(得分:0)

您必须在循环之外定义变量:

    String decide = null
    do {
      ....
      decide = keyboard.nextLine();
    } while (decide.equals("yes"));