import java.util.*;
public class PersonList{
public static void arraylist() {
// create an array list
ArrayList Employee = new ArrayList();
// add elements to the array list
Scanner input = new Scanner (System.in);
System.out.println("Name: ");
Employee.add(input.next());
System.out.println("Year of birth: ");
Employee.add(input.next());
System.out.println("");
Employee.add(input.next());
System.out.println("");
Employee.add(input.next());
System.out.println("");
Employee.add(input.next());
System.out.println("Contents of al: " + Employee);
}
}
我有一个arraylist,它接受用户输入的数据,我需要将有空格的数据存储到一个块中。
我没有添加我将包含的其他内容。我希望能够在名称中添加诸如“John Smith”之类的名称,而不是在两个单独的块中打印John,Smith。我对编程非常陌生,如果它很草率和/或烦人,我会道歉。
答案 0 :(得分:1)
将input.next()
替换为input.nextLine()
。前者通常会根据空格分割你的输入,而后者则会给你整行。
另外,有一个变量的命名约定,要求它们以小写字母开头。此外,不鼓励对列表使用原始类型,并且始终明确指定类型是明智的。您可以将整个arraylist创建行更改为ArrayList<String> employees = new ArrayList<>();
。