gpt4 book ai didi

java - 从 CSV 文件读取数据时遇到问题

转载 作者:行者123 更新时间:2023-11-30 05:33:05 27 4
gpt4 key购买 nike

我正在尝试从 CSV 文件读取数据,然后将每一行放入一个对象中,然后将该对象放入对象的数组列表中。我似乎在这一行遇到错误

int age = fileReader.nextInt();

这是我的完整代码

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testfileio;

import java.io.FileNotFoundException;
import java.io.File;
import java.util.Scanner;
/**
*
* @author gregf
*/
public class TestFIleIO {

/**
* @param args the command line arguments
* @throws java.io.FileNotFoundException
*/
public static void main(String[] args)
throws FileNotFoundException {
Company jam = new Company();

File csv = new File("C:\\Users\\gregf\\Documents\\NetBeansProjects\\TestFIleIO\\employees.csv");
Scanner fileReader = new Scanner(csv);

fileReader.useDelimiter(",|\n");
//skips first row (column headers)
fileReader.nextLine();

while(fileReader.hasNext()) {
String name = fileReader.next();
int age = fileReader.nextInt();
fileReader.nextLine();

try {
jam.setEmployees(new Employee(name, age));
}
catch(Exception ex) {
System.out.println(ex);
}
}

System.out.println(jam);
}

}

错误

Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at testfileio.TestFIleIO.main(TestFIleIO.java:50)
C:\Users\gregf\Documents\NetBeansProjects\TestFIleIO\nbproject\build-impl.xml:1328: The following error occurred while executing this line:
C:\Users\gregf\Documents\NetBeansProjects\TestFIleIO\nbproject\build-impl.xml:948: Java returned: 1
BUILD FAILED (total time: 0 seconds)

一些注意事项:

Employee是一个对象,其名称为:String,年龄:int数据字段

Company 是一个包含 Employee 类型的 ArrayList 的对象,并且有一个 toString 方法来打印所有员工的姓名和年龄。

由于我必须在项目中使用它,所以我不能使用任何库。

如果您有任何想法如何解决这个问题,请分享,非常感谢。

最佳答案

您的输入可能包含一些无法解析为整数的意外字符。这些可能是常规的可打印字符,也可能是不可打印的字符。

检查您的输入数据。让您的应用报告违规数据。检索字符串而不是整数。然后尝试使用 Integer 类进行解析。添加一个 try-catch 来捕获解析错误。出现错误时,报告有问题的字符串的长度和内容。

提示:使用库来帮助读取/写入 CSV。我喜欢 Apache Commons CSV,但还有其他格式可供选择。

关于java - 从 CSV 文件读取数据时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57158312/

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