gpt4 book ai didi

java - Integer.parseInt 无法转换为输入字符串 "1"的整数

转载 作者:行者123 更新时间:2023-11-30 08:16:11 24 4
gpt4 key购买 nike

当我运行应用程序时,它在控制台上返回错误代码。问题是我无法在这一行将字符串转换为 int:

int ogrNo=Integer.parseInt(row[0]);

这是我正在使用的方法:

public void OgrDosyaRead() {
try {
File file = new File("D:\\dosya.txt");

BufferedReader buf = new BufferedReader(new FileReader(file));
String line = null;
while((line=buf.readLine())!= null) {
String[] row = line.split(",");

int No=Integer.parseInt(row[0]);
String Name=row[1];
String Surname=row[2];
String lesson1=row[3];
String lesson2=row[4];
put(No,Name,Surname,lesson1,lesson2);

}

buf.close();

}
catch (Exception error) {
error.printStackTrace();
}

}


public void put(int No,String Name,String Surname,String lesson1,Strşng lesson2) {

这样的错误消息;

java.lang.NumberFormatException: For input string: "1"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Ogrenciler.HashTable.OgrDosyaRead(HashTable.java:178)
at Ogrenciler.MainClass.main(MainClass.java:38)

我的文件 dosya.txt 如下所示:

1,Helen,Dobre,Lesson1,Lesson2

最佳答案

MCVE您的代码工作正常:

public static void main(final String[] args)
{
final String data = "1,Helen,Dobre,Lesson1,Lesson2";
final String[] row = data.split(",");
final int c1 = Integer.parseInt(row[0]);
System.out.println("c1 = " + c1);
}

输出:

c1 = 1

垃圾进垃圾出:

您的问题出在数据中,可能是行的 1, 部分中隐藏的某种空白字符,或者文件使用与 Java 默认编码不同的编码进行编码。

在您的线路上运行以下命令:
System.out.println(String.format("%040x", new BigInteger(1, data.getBytes(Charset.defaultCharset()))));
对于您给出的示例,输出应该是这样的:
312c48656c656e2c446f6272652c4c6573736f6e312c4c6573736f6e32

If you get something different then most likely the file is not encoded with the same encoding that Charset.defaultCharset() is. You will have to find what Charset the file is actually encoded with, this depends on what application was used to create the .txt file. If it was something Windows specific it is probably some Windows default encoding, which is not the Java default.

关于java - Integer.parseInt 无法转换为输入字符串 "1"的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29635074/

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