带有专用 txt 文件的 Java 输入不匹配异常

标签 java type-mismatch inputmismatchexception

我正在开发一个程序,我需要扫描一个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
    }

最佳答案

计算机程序完全按照的指示执行操作。

如果您创建一个需要某些输入的程序,并且该程序告诉您“意外输入”;那么正好有两个逻辑解释:

  1. 您对输入布局(您放入程序中的)的假设是错误的
  2. 假设是正确的,但不幸的是输入数据并不关心这一点

长话短说:这里出错的并不是 IDE。

因此这里的“策略”是:

  1. 在编辑器中打开文本文件
  2. 在 IDE 中打开源代码
  3. 运行调试器;或“手动运行您的代码”;含义:一一浏览说明;对于每个扫描仪操作,检查扫描仪应返回什么;以及该文件在该位置实际包含的内容

关于带有专用 txt 文件的 Java 输入不匹配异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40616266/

相关文章:

java - 使用java中的线程计算列表中的数字总和

go - 无法将数据(类型接口(interface) {})转换为类型字符串 : need type assertion

Java 输入不匹配异常?

java - Java类型不匹配?

java - 我将扫描仪转换为 char 为什么这会给我一个不匹配的异常?

java - 使用 Scanner nextLine 处理 String 时出现 InputMismatchException

java - 捕获异常后请求输入

java - 为什么我的 Java 百分比略有错误?

java - 为自定义存储库方法指定 DELETE HTTP 方法

java - 每次我重新启动时,我的 PC namenode 都没有启动