gpt4 book ai didi

使用 Integer.parseInt(String arg) 时出现 Java NumberFormatException

转载 作者:行者123 更新时间:2023-12-01 23:11:49 25 4
gpt4 key购买 nike

当尝试将字符串的最后部分解析为整数时,我收到 NumberFormatException。异常打印如下:

Exception in thread "main" java.lang.NumberFormatException: For input string: "95
"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at GradeBook.parseDataToStudentArray(GradeBook.java:85)
at GradeBook.main(GradeBook.java:12)

我正在运行一个 for 循环将一个长字符串分解为多个部分,然后从这些部分创建对象。方法如下:

private static Student[] parseDataToStudentArray(String data)
{
Student[] students = new Student[10];
System.out.print(data);
for (int i=0;i<10;i++)
{
String tempStudent = data.substring(0,data.indexOf("\n"));
data=data.substring(data.indexOf("\n")+1);
String firstName= tempStudent.substring(0,tempStudent.indexOf(" "));
tempStudent = tempStudent.substring(tempStudent.indexOf(" ")+1);
String lastName= tempStudent.substring(0,tempStudent.indexOf(" "));
tempStudent = tempStudent.substring(tempStudent.indexOf(" ")+1);
int hw= Integer.parseInt(tempStudent.substring(0,tempStudent.indexOf(" ")));
tempStudent = tempStudent.substring(tempStudent.indexOf(" ")+1);
int quiz= Integer.parseInt(tempStudent.substring(0,tempStudent.indexOf(" ")));
tempStudent = tempStudent.substring(tempStudent.indexOf(" ")+1);
int project= Integer.parseInt(tempStudent.substring(0,tempStudent.indexOf(" ")));
tempStudent = tempStudent.substring(tempStudent.indexOf(" ")+1);
int midterm= Integer.parseInt(tempStudent.substring(0,tempStudent.indexOf(" ")));
tempStudent = tempStudent.substring(tempStudent.indexOf(" ")+1);
int finalExam= Integer.parseInt(tempStudent);
tempStudent = tempStudent.substring(tempStudent.indexOf(" ")+1);
students[i] = new Student(firstName,lastName,hw,quiz,project,midterm,finalExam);
}
return students;
}

非常感谢您的帮助!

我从一个字符串数据开始,如果我 System.out.print(数据)产生

John Smith  92  80  86  76  95
Mary Lamb 66 89 92 100 56
Katy Perry 80 75 89 83 90
Mile Johnson 90 92 95 91 88
Jefferson Hue 75 78 70 82 73
Gabby Alden 83 79 88 94 92
Rubby Barry 89 82 75 90 86
Brian Wilson 78 83 81 89 90
Davis Brown 92 78 50 77 84
Alfred Williams 87 93 67 82 95

最佳答案

我强烈建议您使用String#split它返回一个数组。由于姓名和第一个数字之间的空格数量不同,因此您可以使用 split("\\s+") 分割多个空格。例如

String line = "John Smith  92  80  86  76  95";
String[] tokens = line.split("\\s+");

分割将返回

tokens = { "John", "Smith", "92", "80", "76", "95" };

前两个索引生成名称并解析其余索引。由于每行都有相同数量的标记,因此它应该可以在循环中正常工作。

String firstName = tokens[0];
String lastName = tokens[1];
int hw = Integer.parseInt(tokens[2]);
...
<小时/>

注意请参阅下面的 @janos 评论,了解具有相同功能的另一个选项

关于使用 Integer.parseInt(String arg) 时出现 Java NumberFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21813505/

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