数组列表中的分隔符无法正常工作

时间:2018-04-15 15:09:40

标签: java arraylist

这是我的代码:

while(instructorInput.hasNextLine()) {
     Scanner lineSeperator = new Scanner(instructorInput.next());
     lineSeperator.useDelimiter(",");
     lines.add(lineSeperator.next());
}

System.out.print(lines.get(0) + " ");
System.out.println(lines.get(1));

此代码输出:

5005 Lizards

代码应输出:

5005 Black Lizards

我尝试过使用:

lines.add(lineSeperator.nextLine());

但这也不起作用。

我正在尝试从文件中读取线条的样子:

5005,Black Lizards,USA

1 个答案:

答案 0 :(得分:0)

lines.add(lineSeperator.next());只会添加第一个值

使用分隔符

后需要迭代lineSeprator
while(instructorInput.hasNextLine()) {
     Scanner lineSeperator = new Scanner(instructorInput.next());
     lineSeperator.useDelimiter(",");
     while(lineSeperator.hasNext())//use another while to iterate
        lines.add(lineSeperator.next());
}

这是我试过的

public class Test{
public static void main(String args[]) {
      Scanner lineSeperator = new Scanner("5005,Black Lizards,USA");
         lineSeperator.useDelimiter(",");
         while(lineSeperator.hasNext())
         System.out.println(lineSeperator.next());

  }
}

输出

5005
Black Lizards
USA