扫描字符串并存入ArrayList中

huangapple go评论95阅读模式
英文:

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&lt;String&gt; yourList = new ArrayList&lt;&gt;();
        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(&quot;,&quot;, yourList));

huangapple
  • 本文由 发表于 2020年9月25日 20:50:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64064534.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定