How to get a multiple-line input from a user in Java and then store the input in an array of type string where every line is an element of the array

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

How to get a multiple-line input from a user in Java and then store the input in an array of type string where every line is an element of the array

问题

["Name Alex", "Age 25", "Nationality Sweden", "Spoken Languages Swedish and English"]
英文:

For example,
input:

Name Alex
Age 25
Nationality Sweden
Spoken Languages Swedish and English

output:

["Name Alex", "Age 25", "Nationality Sweden", "Spoken Languages Swedish and English"]

答案1

得分: 0

用Scanner类的帮助,您可以从命令行输入并将每一行存储到String数组或ArrayList集合中。

public static void main(String[] args) {

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

        while (s.hasNextLine()) {
            String line = s.nextLine();
            in.add(line);

            if (line != null && line.equalsIgnoreCase("END")) {
                System.out.println("Output list: " + in);
                break;
            }
        }
}
英文:

With the help of Scanner class you can take input from cmd and store each line into Array of String or In ArrayList<String> collection.

public static void main(String[] args) {

    ArrayList&lt;String&gt; in = new ArrayList&lt;String&gt;();
    Scanner s = new Scanner(System.in);

    while (s.hasNextLine()) {
        String line = s.nextLine();
        in.add(line);

        if (line != null &amp;&amp; line.equalsIgnoreCase(&quot;END&quot;)) {
            System.out.println(&quot;Output list : &quot; + in);
            break;
        }

    }

}

huangapple
  • 本文由 发表于 2020年10月11日 02:20:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/64296789.html
匿名

发表评论

匿名网友

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

确定