我使用scan read的java程序不会停止执行

时间:2013-04-17 19:37:27

标签: java

我是Java世界的新手。我写了这个程序,它读取字符串数组......当我运行它时,它永远不会停止?!!我应该添加/更改什么才能使其结束扫描?

import java.util.*;

public class Ex21 {
public static void main(String[] args) {
    int i, n = 5;
    String c;
    ArrayList<String>words = new ArrayList<>();
    System.out.println("Enter multi strings: ");
    Scanner input = new Scanner(System.in);
    boolean loop = true;
    while(loop) {
        words.add(input.next());
        Collections.sort(words);
        System.out.println("The sorted list is: " + words);
    }
    }

}

3 个答案:

答案 0 :(得分:2)

根据定义,while循环继续执行其正文,直到其条件(在本例中为变量loop)计算为false。您从未在loop - 循环的正文中将false设置为while,因此条件永远不会评估为false,并且循环将永远不会结束。

此外,您似乎想要对用户输入的单词列表进行排序。我不建议在循环的每次迭代中调用Collections.sort。也许考虑使用一种数据结构来保持其元素自己排序,例如TreeSet。或者,至少在循环之后直接调用sort方法一次。

答案 1 :(得分:2)

while(condition) {
     /* do something */
}

表示/ *做某事* /发生,除非条件==假,在你的情况下它始终是真的,这就是为什么它不会停止。所以Java在你的情况下表现良好。

答案 2 :(得分:0)

while(loop) loop在您的计划中始终具有值true,这就是所谓的endless loop,正如名称所说,它永远不会结束,这就是您所遇到的。

要进行循环停止,您必须在满足某些条件时将loop的值设置为false,或使用关键字break终止循环。

条件可能是例如有一个单词巫婆让你的循环在输入时终止,类似于"exit"

以下是如何将loop设置为false

的示例
String word = input.next();
boolean loop = ! "exit".equalsIgnoreCase(word);
while (loop) {
    words.add(word);
    Collections.sort(words);
    System.out.println("The sorted list is: " + words);
    word = input.next();
    loop = ! "exit".equalsIgnoreCase(word);
}
System.out.println("Bye!");

以下是另一个使用break

取消循环的示例
while (true) {
    String word = input.next();
    if("exit".equalsIgnoreCase(word)) {
        break;
    }
    words.add(word);
    Collections.sort(words);
    System.out.println("The sorted list is: " + words);
}
System.out.println("Bye!");

请注意,单词exit在您的arraylist可以包含的集合中被禁止,您可以更改程序,但也可以保存它。

相关问题