【发布时间】:2019-08-03 12:04:09
【问题描述】:
我想在java中打印一个数组List,但是为什么开头会打印一个逗号?
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
String name;
List<String> nameList= new ArrayList<>();
for(int i=0;i<=n;i++) {
name=sc.nextLine();
nameList.add(name);
}
System.out.println(nameList);
}
And this is the result i got
2
ABC
XYZ
[, ABC, XYZ]
如您所见,为什么在 ABC 之前打印逗号?
【问题讨论】:
-
您应该在添加到列表之前检查它。因为在插入数字后你按 Enter.
name = sc.nextLine(); if (!name.equals("")) nameList.add(name);