2013-11-25 24 views
0

我想從tableLineScanner添加兩行,從Scanner得到它的行稱爲tableScanner沒有這樣的元素例外,配音線掃描儀

無論如何,我得到這些錯誤

at java.util.Scanner.throwFor(Scanner.java:907) 
at java.util.Scanner.next(Scanner.java:1416) 
at Database.main(Database.java:77) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
at java.lang.reflect.Method.invoke(Method.java:606) 
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120) 

但在代碼波紋管,我不明白爲什麼我得到這個錯誤。因爲我檢查他們是否有兩條線路可用,並且由於不參與而存在。

if((tableLineScanner.hasNextLine()&&(tableLineScanner.hasNextLine()))){ //Checks if it exists two available lines. 
    fieldInput = (tableLineScanner.next() + " " + (tableLineScanner.next().replaceAll("[()]", ""))+","); 
    tableFields.add(fieldInput); 
    System.out.println("ADDING: " + fieldInput + " to tableField array list"); 
} 

請幫助:(

+1

你不能調用'hasNextLine ()'兩次,並期望它有兩行可用。你必須再次調用next()(或更好,nextLine()),然後再調用hasNextLine()。 – aioobe

回答

3

的方法Scanner#hasNextLine()只是告訴你,如果有一個更優惠的產品線。如果調用它兩次,它仍然只是告訴你,如果有一個更優惠的產品線。你可以把它叫做n倍,但它只會告訴你的下一行

呼叫Scanner#nextLine(),然後你可以再次測試是否有可用另一條線

總是這樣做的:。

  1. 測試,如果更多的數據是可用的
  2. 讀取數據
  3. 測試,如果更多的數據是可用的
  4. ...

if (tableLineScanner.hasNextLine()) { 
    String firstLine = tableLineScanner.nextLine(); 

    if (tableLineScanner.hasNextLine()) { 
     String secondLine = tableLineScanner.nextLine().replaceAll(...); 

     tableFields.add(firstLine + secondLine); 
    } else { 
     // No-second-line error handling goes here 
    } 
} else { 
    // No-first-line error handling goes here (if any) 
} 
+0

由於我在編程方面相當習慣,我不確定這將如何實現。 (我太累了,真的沒有任何精力,我很快就要睡覺了) if(tableLineScanner.next(2)){?或類似的東西? –

+0

非常感謝你! –