我正在开发一个程序,我需要扫描一个txt文件。保证 txt 文件在不同类型出现的位置和时间方面遵循特定格式。我尝试在程序中利用这一点,并使用扫描仪将我知道的整数部分以及 double 和字符串放入整数中。当我运行我的程序时,它告诉我有一个类型不匹配异常,我知道由于 txt 文件的格式,我的所有类型都匹配,所以我如何让 IDE 认为这是可以的。这是有问题的代码块,它会有所帮助。
ArrayList<Student>studentList=new ArrayList<Student>();//makes a new Array list that we can fill with students.
FileInputStream in=new FileInputStream("studentList.txt");//inputs the text file we want into a File Input Stream
Scanner scnr=new Scanner(in);//Scanner using the Input Stream
for(int i=0;i<scnr.nextInt();i++)//we know the first number is the number of minor students so we read in a new minor that number of times
{
Undergrad j=new Undergrad();//make a new undergrad
j.setDegreeType("MINOR");//make the degree type minor because we know everyone in this loop is a minor.
j.setFirstName(scnr.next());//we know the next thing is the student's first name
j.setLastName(scnr.next());//we know the next thing is the student's last name
j.setID(scnr.nextInt());//we know the next thing is the student's ID
j.setGPA(scnr.nextDouble());//we know the next thing is the student's GPA
j.setCreditHours(scnr.nextDouble());//we know the next thing is the student's credit hours
studentList.add(j);//Finally, we add j to the arraylist, once it has all the elements it needs
}
最佳答案
计算机程序完全按照您的指示执行操作。
如果您创建一个需要某些输入的程序,并且该程序告诉您“意外输入”;那么正好有两个逻辑解释:
- 您对输入布局(您放入程序中的)的假设是错误的
- 假设是正确的,但不幸的是输入数据并不关心这一点
长话短说:这里出错的并不是 IDE。
因此这里的“策略”是:
- 在编辑器中打开文本文件
- 在 IDE 中打开源代码
- 运行调试器;或“手动运行您的代码”;含义:一一浏览说明;对于每个扫描仪操作,检查扫描仪应返回什么;以及该文件在该位置实际包含的内容
关于带有专用 txt 文件的 Java 输入不匹配异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40616266/