英文:
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<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;
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论