将字符串扫描到 ArrayList
Scan string into an ArrayList
我想扫描一些字符串(不带 ,)并打印出来(带 ,)。
我可以知道我应该如何更改我的代码吗?
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);
}
}
您将整行输入为单个字符串而不是单独的字符串:
while(sc.hasNext()){
yourList.add(sc.next()); // next() instead of nextLine
}
如果要打印以逗号分隔的列表中的单词,请使用 String.join:
System.out.println(String.join(",", yourList));
我想扫描一些字符串(不带 ,)并打印出来(带 ,)。 我可以知道我应该如何更改我的代码吗?
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);
}
}
您将整行输入为单个字符串而不是单独的字符串:
while(sc.hasNext()){
yourList.add(sc.next()); // next() instead of nextLine
}
如果要打印以逗号分隔的列表中的单词,请使用 String.join:
System.out.println(String.join(",", yourList));