简体   繁体   中英

my java program using scan read does not stop execution

I am a newbee in the Java world. I wrote this program which reads in string array... When I run it, it never stops?!! what shall I add /change to make it end scanning?

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);
    }
    }

}

A while loop by definition continues executing its body until its condition (in this case the variable loop ) evaluates to false . You never set loop to false in the body of the while -loop, hence the condition will never evaluate to false and the loop will never end.

Additionally, it seems like you want to sort a list of words entered by the user. I wouldn't advise calling Collections.sort on every iteration of the loop. Maybe look into using a data structure that keeps its elements sorted on its own, such as a TreeSet . Or, at least, only call the sort method once, directly after the loop.

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

means /* do something */ happens unless condition == false, in your case it alwats true, that is why it doesn't stop. So Java behaves ok in your case.

while(loop) with loop always having the value true in your program is a so called endless loop , as the name says it never ends and this is what you are experiencing.

To make a loop stop you have to set the value of loop to false if some condition is fulfilled or terminate the loop using the key word break .

A condition may be for example having a certain word witch lets your loop terminate when it is entered, something like "exit"

Here is an example how you could set loop to 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!");

Here is an other example how you could cancel the loop using 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!");

Note that the word exit is banned from the set that your arraylist can contain, You can change the program though to have it saved too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM