2011-10-06 32 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