import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class CSVReader
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner scanner = new Scanner(new File("Lunch.csv"));
ArrayList<String> AccountNum = new ArrayList<String>();
ArrayList<String> AccountBal = new ArrayList<String>();
scanner.useDelimiter(",");
while(scanner.hasNext())
{
AccountNum.add(scanner.next());
AccountBal.add(scanner.next());
}
scanner.close();
display(AccountNum, AccountBal);
}
public static void display(ArrayList AccountNum, ArrayList AccountBal)
{
System.out.println("\nThe size of the list is " + AccountNum.size());
for(int x = 0; x < AccountNum.size(); ++x)
{
System.out.println("position " + x + " Number: " + AccountNum.get(x));
System.out.println("position " + x + " Number: " + AccountBal.get(x));
}
}
}
该程序应该从一个CSV文件读取到两个数组中。它编译得很好,但是当我运行它时会抛出NoSuchElementException异常。该程序仅在使用一个数组时才起作用。有谁知道它为什么抛出这个异常以及如何解决它?带两个ArrayList的NoSuchElementException
您在'scanner.hasNext()'后面使用'scanner.next'两次()' – lifus 2013-05-01 17:13:44
哪一行引发异常,你知道吗?此外,你的while循环似乎假设将会添加偶数个元素。是这样吗?也许从csv和最后一个'AccountBal.add(scanner.next())中有奇数个元素;'问题出在哪里...... – 2013-05-01 17:14:47