线程"main"中的异常java.lang.ArrayIndexOutOfBoundsException:1对输入文件程序

use*_*794 -2 java swing indexoutofboundsexception

我收到一条消息:线程"main"中的异常java.lang.ArrayIndexOutOfBoundsException:1尝试运行以下代码时.该程序从文本文件中获取输入,执行一些工资编号,并输出他们的总工资.

这是文本文件的内容:http: //m.uploadedit.com/b034/139892732049.txt

 package payroll;

 import java.io.File;
 import java.io.FileNotFoundException;
 import java.util.Scanner;
 import javax.swing.JOptionPane;

 public class PayRoll
 {
    private String empName;
    private int hours;
    private int hourlyPayRate;

    public PayRoll(String name, int hh, int rr)
    {
        empName = name;
        hours = hh;
        hourlyPayRate = rr;      
    }  

    public String getName()
    {
        return empName;
    }

    public double getPay()
    {
        if(hours <= 40)
            return hours * hourlyPayRate;
        else
            return (40 * hourlyPayRate) + (hours - 40) * 1.5 * hourlyPayRate;
    }

    public static void main(String[] args)
    {  
        Scanner inFile = null;

        try
        {
        inFile = new Scanner(new File("payroll.txt"));
        }
        catch(FileNotFoundException e)
        {
           e.printStackTrace();
        }

        String name;
        String first;
        String last;
        int hh;
        int rr;
        String result = "Details of employees:\n";

        while(inFile.hasNextLine())
        {
            String line = inFile.nextLine();

            String tokens[] = line.split(" ");

           first = tokens[0];
           last = tokens[1];
            hh = Integer.parseInt(tokens[2]);
            rr = Integer.parseInt(tokens[3]);

            name = first + " " + last;

            PayRoll payroll = new PayRoll(name, hh, rr);

            result += "Name: " + payroll.getName() + ", GrossPay: $" + payroll.getPay() + "\n";
        }

        JOptionPane.showMessageDialog(null, result);

        inFile.close();
    }
 }
Run Code Online (Sandbox Code Playgroud)

Sca*_*bat 5

问题是您的文件中有空行会导致令牌长度为零的令牌数组

每次读取后验证令牌数组的长度.

  if (token == null || token.length != 4) continue;
Run Code Online (Sandbox Code Playgroud)

或者当然Duncan建议只是跳过空行或两者(更好的选择).

  if (line == null || line.trim().length() < 1) continue;
Run Code Online (Sandbox Code Playgroud)

这两项检查都应该完成,也可以单独报告.