如何停止从用户那里获取输入

时间:2018-09-25 10:29:44

标签: java arrays sorting

我想创建一个字符串ArrayList,其中输入来自用户,但输入无尽。用户需要时如何停止它。

public class SortingString {

public static void main(String args[]) {

    Scanner in = new Scanner(System.in);
    ArrayList<String> words = new ArrayList<String>();

    System.out.println("Enter the words:");

    while (in.hasNext()) {
        words.add(in.nextLine());
    }

    Collections.sort(words);
}

编辑:谢谢大家的回答。现在正在工作。

2 个答案:

答案 0 :(得分:2)

那怎么办?

public class SortingString {
    public static void main(String args[]) {

        Scanner in = new Scanner(System.in);
        ArrayList<String> words = new ArrayList<String>();

        while (in.hasNext()) {
            System.out.println("Enter the word:");
            words.add(in.nextLine());
            System.out.println("Do you want to continue? (y/n)");
            in.hasNext();
            if (!in.nextLine().equalsIgnoreCase("y")) {
                break;
            }
        }
        Collections.sort(words);

        in.close(); // Don't forget to close the stream !!
    }
}

一种更优雅的方式:(编辑发布完整代码)

public static void main(String args[]) {
    Scanner in = new Scanner(System.in);
    ArrayList<String> words = new ArrayList<String>();

    System.out.println("Enter the words or write STOP to exit:");
    while (in.hasNext()) {
        String inputLine = in.nextLine();
        if (inputLine.equalsIgnoreCase("STOP")) {
            break;
        }
        words.add(inputLine);
    }

    Collections.sort(words);

    System.out.println("The words sorted:");
    System.out.println(words);

    in.close(); // Don't forget to close the stream !!
}

答案 1 :(得分:1)

这是一种可能的解决方案,其中“退出”字词不会添加到private void Popup_Opened(object sender, System.EventArgs e) { SetAutoYAxisCommand = new RelayCommand1(SetAutoYAxis, o => true); } <Popup Opened="Popup_Opened"> 列表中。

words