[英]Using multiple scanners to read file line by line resulting in noSuchElementException
我不確定何時會收到沒有此類元素的異常。 掃描儀似乎無法正確讀取我的文件,這似乎是一個問題,但是我不確定我要去哪里。
我正在讀取文件,然后使用掃描儀逐行掃描。 但是,當我嘗試執行此操作時,會遇到異常行為,例如缺少行或filenotfound異常。
public static void readMylifeLikeABook(String fileName,int maxItems) {
// Read file line by line with different elements on each line
int bookCount=0;
int movieCount = 0;
Book [] bookItem =new Book[maxItems];
Movie [] movieItem =new Movie[maxItems];
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
Scanner line;
while (scanner.hasNext() && ((bookCount+movieCount)<maxItems)) {
line = new Scanner(scanner.nextLine()); // scan next line
if (line.next().contains("Movie")){
movieItem[movieCount]= new Movie();
movieItem[movieCount].setMediaType("Movie");
movieItem[movieCount].setTitle(scanner.nextLine());
movieItem[movieCount].setRef(scanner.nextLine());
movieItem[movieCount].setPrice(Double.valueOf(scanner.nextLine()));
movieItem[movieCount].setDirector(scanner.nextLine());
movieItem[movieCount].setActor(scanner.nextLine());
System.out.println(movieItem[movieCount].getTitle());
movieCount++;
line.close(); // close line
}
else if (scanner.next().contains("Book")){
bookItem[bookCount]= new Book();
bookItem[bookCount].setMediaType("Book");
bookItem[bookCount].setTitle(scanner.nextLine());
bookItem[bookCount].setRef(scanner.nextLine());
bookItem[bookCount].setPrice(Double.valueOf(scanner.nextLine()));
bookItem[bookCount].setAuthor(scanner.nextLine());
System.out.println(bookItem[bookCount].getTitle());
bookCount++;
line.close(); // close line
}
}
scanner.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
//System.out.println(count);
for (int i=0;i<(bookCount+movieCount);i++) {
System.out.println(bookItem[i] +"\n\n "+ movieItem[i]);
}
}
嗯,是否可以提供正在讀取的文件? 這很可能是該文件的一個問題,就像Scanner對象沒有要讀取的下一行一樣,它將引發異常。 確保文件具有所需的行數。
您在構造line
之后立即調用line.next()
。 您需要這樣做嗎? 如果是這樣,也許您首先需要調用hasNext()
以確保那里有一個令牌。
(我很確定line.next()
如果沒有令牌,則拋出NoSuchElementException
。)
另外,對照文件格式檢查代碼。 文件中是否有空行?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.