我在我的java项目中收到下面的异常。NoSuchElementException扫描器java
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at com.ooad.ooadfirstassignment.Employee.readData(Employee.java:25)
at com.ooad.ooadfirstassignment.Salaried.readData(Salaried.java:16)
at com.ooad.ooadfirstassignment.Factory.<init>(Factory.java:21)
at com.ooad.ooadfirstassignment.MainClass.main(MainClass.java:25)
的代码如下:
================================= ====================
public class MainClass {
/**
* @param args
*/
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
FileInputStream empTextStreamIn = null;
try
{
empTextStreamIn = new FileInputStream("Employee.txt");
}
catch(FileNotFoundException fex)
{
System.out.println("Employee File not found");
fex.printStackTrace();
}
Factory f = new Factory(empTextStreamIn);
empTextStreamIn.close();
}
}
======================= =============================================
public class Factory
{
public Factory(FileInputStream empTextStreamIn)
{
// TODO Auto-generated constructor stub
int empType;
String EmpID = null,DeptID = null;
double salary=0;
Scanner sc = new Scanner(empTextStreamIn);
while(sc.hasNextLine())
{
empType = sc.nextInt();
switch (empType)
{
case 1:Salaried salr = new Salaried(empTextStreamIn);
salr.readData();
System.out.println("EmpType="+empType+" EmpID="+EmpID+" DeptID="+DeptID+" Salary="+salary);
代码继续,所以这是主要部分。
下一个Employee类
public class Employee
{
String EmpID, DeptID; //Unique detail for Employee class
protected Scanner sc;
Employee()
{
}
public Employee(FileInputStream empTextStreamIn)
{
// TODO Auto-generated constructor stub
sc = new Scanner(empTextStreamIn);
}
void readData()
{
String EmpID = sc.next();
String DeptID = sc.next();
}
}
工薪阶层
public class Salaried extends Employee
{
double salary; //Unique detail for Salaried class
public Salaried(FileInputStream empTextStreamIn)
{
super(empTextStreamIn);
}
void readData()
{
super.readData();
salary = sc.nextDouble();
}
}
请帮助我,我要去哪里错了。
downvote的任何特定原因? – 2012-02-14 07:57:47
即使下面这行是空的,hasNextLine()是否返回true?你有没有试图用换行符结束文件? (即最后一行末尾没有换行符) – 2012-02-14 08:18:59
将Employee类中的readDate函数更改为“while(sc。hasNextLine()) { \t empType = sc.nextInt(); \t EmpID = sc.next(); \t DeptID = sc.next(); }“和工资readData()函数作为”super.readData(); while(sc.hasNext()) salary = sc.nextDouble(); – 2012-02-14 13:15:35