gpt4 book ai didi

java - NoSuchElementException 扫描器 java

转载 作者:行者123 更新时间:2023-12-02 00:29:54 26 4
gpt4 key购买 nike

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

代码还在继续,所以这是主要部分。

接下来是员工类

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();


}

}

请帮助我解决问题。

最佳答案

似乎您的测试文件包含的数据少于您尝试读取的数据,因为这就是 this exception is thrown 的原因。最好使用 hasNext() 检查输入是否有任何下一个元素。方法。

关于java - NoSuchElementException 扫描器 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9273368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com