2011-10-06 56 views

回答

2

我猜那是因爲你有:

while (inputFile.hasNext()) 

使用Scanner.hasNextLine

編輯

我與樣品輸入測試你的代碼。我明白你的意思了。

while (inputFile.hasNextLine()) { 
      employeeID = inputFile.nextLine(); // Read info from first line and store it in employeeID 
      employeeName = inputFile.nextLine(); // Read info from next line and store it in employeeName 

      userInput = JOptionPane.showInputDialog("Employee Name: " + employeeName + "\nEnter number of" + // display employee name and ask for number of hours worked 
      " hours worked:"); 

      hours = Double.parseDouble(userInput); // Store user's parsed input into hours 
      wageRate = inputFile.nextDouble(); // Read info from next line and store it in wageRate 
      taxRate = inputFile.nextDouble(); // Read info from next line and store it in taxRate 

使用hasNextLine作爲你的情況只會確保對nextLine下一個電話將是有效的。但是,您的電話nextLine兩次,然後撥打nextDouble之後。您可以(1)確保您的電話與文件完全匹配,或者(2)每次您撥打下一個時檢查是否有下一個令牌。我認爲(1)是你的問題。

我能夠用下面的修復程序:

while (inputFile.hasNextLine()) { 
    employeeID = inputFile.nextLine(); 
    employeeName = inputFile.nextLine(); 
    userInput = JOptionPane.showInputDialog("Employee Name: " + employeeName + "\nEnter number of hours worked:"); 
    hours = Double.parseDouble(userInput); 
    wageRate = Double.parseDouble(inputFile.nextLine()); 
    taxRate = Double.parseDouble(inputFile.nextLine()); 
    Paycheck paycheck = new Paycheck(employeeID, employeeName, wageRate, taxRate, hours); 
    paycheck.calcWages(); 
    JOptionPane.showMessageDialog(null, "Employee ID: " + 
      paycheck.getEmployeeID() + "\nName: " + 
      paycheck.getEmployeeName() + "\nHours Worked: " + 
      hours + "\nWage Rate: $" + 
      money.format(paycheck.getWageRate()) + "\nGross Pay: $" + 
      money.format(paycheck.getGrossPay()) + "\nTax Rate: " + 
      paycheck.getTaxRate() + "\nTax Withheld: $" + 
      money.format(paycheck.getTaxWithheld()) + "\nNet Pay: $" + 
      money.format(paycheck.getNetPay())); 
} 

文件內容:

00135 
John Doe 
10.50 
0.20 
00179 
Mary Brown 
12.50 
1.20 
+0

我正在檢查inputFile,它是我創建的Scanner類的實例,是否具有.txt文檔的下一行。我不明白你在問我什麼。它讀取一切正常,但是當有更多的信息要閱讀時,它會崩潰。 – Leon

+0

您正在使用[hasNext()](http://download.oracle.com/javase/1,5,0/docs/api/java/util/Scanner.html#hasNext()),然後您致電[ nextLine()](http://download.oracle.com/javase/1,5,0/docs/api/java/util/Scanner.html#nextLine())兩次。所以最終你會得到一個「java.util.NoSuchElementException:No line found」。這兩種方法有不同的分隔符。您正逐行閱讀,因此請檢查新行。 – DarkByte

+0

唯一的問題是,我有這樣的數據: (1號線)00135 (線2)John Doe的 (第3行)10.50 (線4)0.20 (線路5)*空* (第6行) 00179 (第7行)Mary Brown etc .. 如果我撥打一次,在我的第二個循環中,它會在我的中顯示員工的ID。 如果我撥打兩次,它會在JOptionPane中正確顯示員工的姓名,但是我會收到錯誤 – Leon