首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >导致此错误消息的原因是什么?

导致此错误消息的原因是什么?
EN

Stack Overflow用户
提问于 2013-03-27 23:06:23
回答 2查看 108关注 0票数 0

这是我的代码,注释总结了程序应该做的事情。

代码语言:javascript
运行
复制
// This program will read in from a file a number that tells how many
// wages and hours worked the file contain. And then calculates the
// salary
import java.util.*;
import java.text.*;

public class Lab10
{
        public static void main(String[] args)
        {
          // Declare variables
          Scanner scan = new Scanner(System.in);
          DecimalFormat fmt = new DecimalFormat("0.00");
          String name;
          double wages;
          double hoursWorked;
          double salary;
          int numCalculate;
          int EmployeeNumber ;
          int i = 0 ;

          // Read in how many employees the file contains
          EmployeeNumber =scan.nextInt() ;

          // for loop that reads and records the name hoursworked and wages , and prints out the information
          for ( ; i < EmployeeNumber +1; i ++ )
          {
           name = scan.next () ;
           wages = scan.nextDouble() ;
           hoursWorked = scan.nextDouble() ;

           salary = calculateSalary(wages,hoursWorked) ;
           System.out.println(name +" worked " +fmt.format(hoursWorked) + " with a wage of " + "$" +fmt.format(wages) + " and got paid $" +fmt.format(salary) );
          }
          // End of control loop

         } // End of main method

         public static double calculateSalary(double wages, double hoursWorked)
         {
//Declare constants
          final int OVERTIME_BREAK = 40;
          final double OVERTIME_MULTIPLE = 1.5;
          double salary = 0 ;

          //Calculate salary

          if(hoursWorked > OVERTIME_BREAK)
          {
          salary = (hoursWorked - OVERTIME_BREAK) * wages * OVERTIME_MULTIPLE + hoursWorked * wages;
          }
          else
          {
            salary = hoursWorked * wages;
          }
          // Return the salary
           return salary ;

         } // end of calculateSalary method
} // End of Lab10 class

使用此输入文件时:

代码语言:javascript
运行
复制
3
Smith 12.50 25
Jones 25.89 60
Brown 7.86 19.89

我得到了我想要的输出,但这条消息附加在末尾:

代码语言:javascript
运行
复制
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:855)
    at java.util.Scanner.next(Scanner.java:1364)
    at Lab10.main(Lab10.java:32)

有人能告诉我这意味着什么以及如何修复它吗?

EN

回答 2

Stack Overflow用户

发布于 2013-03-27 23:11:30

你的循环次数太多了。

您有3个员工,因此应该像这样循环:

代码语言:javascript
运行
复制
for ( ; i < EmployeeNumber; i ++ )
{
    name = scan.next () ;
    ...
 }
票数 2
EN

Stack Overflow用户

发布于 2013-03-27 23:32:15

Java的数组索引从0开始,所以如果你有3个元素,它们存储在0,1和2。正如上面在for循环中所说的,如果你只放i< EmplyeeNumber就足够了,而不是EmployeeNumber + 1。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15662208

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档