使用Scanner从文件读取时获取异常

时间:2015-11-01 17:33:14

标签: java arraylist try-catch text-files

我试图让程序读取文本文件的内容,将每一行存储在一个数组中,然后以有序的方式为每种类型输出结果。我将已排序的部分放下,但每次运行主程序时,我都会收到try / catch的错误消息(这仍然是正在进行的工作)

package p20;
import java.io.*;
import java.util.*;

public class EmployeeOrderingDemo {

public static void main(String[] args)  {
    Scanner input=null;
    ArrayList<EmployeeFX> employeeList=new ArrayList<EmployeeFX>();
    try {
        FileReader Info=new FileReader("P01_DATA.txt");
        input=new Scanner(Info).useDelimiter("\\s\\s+");
    }
    catch(FileNotFoundException noFile) {
        System.out.println("Can't open file");
        System.exit(1);
    }

    try {
        while(input.hasNextLine()) {
            employeeList.add(new EmployeeFX(input.nextInt(),input.next(),input.next(), input.nextBoolean(), input.nextInt()));          
            input.nextLine();
        }
    }
    catch(NoSuchElementException element) {
        System.err.println("Wrong type of file");
        System.exit(1);
    }
    catch(IllegalStateException state) {
        System.err.println("Couldn't read from file");
        System.exit(1);
    }
    if(input!=null) {
        input.close();
    }
  }
}

我收到的消息是&#34;错误的文件类型&#34;。是因为我需要跳过文本文件的标题吗?

这是EmployeeFX代码

package p20;

public class EmployeeFX {

private int id;
private String firstName;
private String lastName;
private boolean salaried;
private double salary;

public EmployeeFX(int id, String firstName, String lastName,boolean salaried, int salary) {
    this.id=id;
    this.firstName=firstName;
    this.lastName=lastName;
    this.salaried=salaried;
    this.salary=salary;
  }
}

这是堆栈跟踪

java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at p20.EmployeeOrderingDemo.main(EmployeeOrderingDemo.java:26)

这是输入文本文件

id  firstName   lastName    salaried    salary

200 Caroline    James   false   37654
2   Julian  James   false   46499
1   Conor   Habgren true    88767
10  Tillie  Donalan true    98456
15  Alice   Jeanu   true    72821
12  Fred    Habgren false   28767
103 Mary    Donalan false   28456
135 Ed  Jeanu   true    52821

1 个答案:

答案 0 :(得分:1)

请尝试使用以下类的rho = x*cos(theta) + y*sin(theta)方法代码:内联查找注释。

main