我在我的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