英文:
Scan string into an ArrayList
问题
import java.util.*;
class Main {
public static void main(String[] args) {
ArrayList<String> yourList = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
yourList.add(sc.next()); // Change sc.nextLine() to sc.next()
}
System.out.println(yourList);
}
}
英文:
I want to scan some Strings (without ,) and print them out (with ,).
May I know how should I change my code?
> Example: Test input: Apple Pen Water
>
> Correct output: [Apple, Pen, Water]
>
> Current code output: [Apple Pen Water]
import java.util.*;
class Main {
public static void main(String[] args) {
ArrayList<String> yourList = new ArrayList<>();
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
yourList.add(sc.nextLine());
}
System.out.println(yourList);
}
}
答案1
得分: 2
当你输入整行作为一个单独的字符串而不是分开的字符串时:
```java
while(sc.hasNext()){
yourList.add(sc.next()); // 使用 next() 而不是 nextLine
}
英文:
You're inputting the entire line as a single string instead of separate strings:
while(sc.hasNext()){
yourList.add(sc.next()); // next() instead of nextLine
}
答案2
得分: 1
如果您想要将列表中的单词以逗号分隔打印出来,可以使用String.join方法:
System.out.println(String.join(",", yourList));
英文:
If you want to print words from list separated with comma, use String.join:
System.out.println(String.join(",", yourList));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论