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