gpt4 book ai didi

java - 如何停止获取用户输入

转载 作者:行者123 更新时间:2023-12-01 19:47:48 24 4
gpt4 key购买 nike

我想创建一个字符串 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);
}

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

最佳答案

什么?

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 !!
}

关于java - 如何停止获取用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52496017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com