好的,所以我在编程任务上遇到了很多麻烦。我们将从文本文件中读取信息,并使用我们创建的某些方法对其进行格式化。我能够很好地从文本文件的第一行读取信息,但后来我收到错误。我的代码如下:
String name1 = scan.nextLine();
String name2 = scan.nextLine();
scan.close();
int length = name1.length();
int count = 0;
int a = 0;
int b = 1;
while(end != true)
{
String check = name1.substring(a,b);
a++;
b++;
count++;
char z = check.charAt(0);
if(z == '0' || z == '1' || z == '2' || z == '3' || z == '4' || z == '5' || z == '6' || z == '7' || z == '8' || z == '9')
{
end = true;
}
if(count == length)
{
end = true;
}
}
String number1 = name1.substring(count,length);
int number01 = Integer.parseInt(number1);
name1=name1.substring(0, count-1);
int d = name1.indexOf(" ");
int length1 = name1.length();
String name1first = name1.substring(0,d);
name1first = name1first.trim();
String name1last = name1.substring(d,length1);
name1last = name1last.trim();
System.out.println(name1first);
System.out.println(name1last);
System.out.println(number01);
length = name2.length();
int countt = 0;
int aa = 0;
int bb = 1;
while(end != true)
{
String check = name2.substring(aa,bb);
aa++;
bb++;
countt++;
char z = check.charAt(0);
if(z == '0' || z == '1' || z == '2' || z == '3' || z == '4' || z == '5' || z == '6' || z == '7' || z == '8' || z == '9')
{
end = true;
}
if(countt == length)
{
end = true;
}
}
String number2 = name2.substring(countt,length);
int number02 = Integer.parseInt(number2);
name2=name2.substring(0, countt-1);
d = name2.indexOf(" ");
int length2 = name2.length();
String name2first = name2.substring(0,d);
name2first = name2first.trim();
String name2last = name2.substring(d,length2);
name2last = name2last.trim();
System.out.println(name2first);
System.out.println(name2last);
System.out.println(number02);
我收到此错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Jennifer Sutter 52114"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Salary.main(Salary.java:101)
答案 0 :(得分:0)
这显然是为什么你得到那个例外:
您正在尝试将“Jennifer Sutter 52114”转换为整数。
解决方法是在尝试呼叫try{}catch()
时首先使用Integer.parseInt()
阻止。
我认为你正在尝试获取最后一点字符串并将其转换为整数:并且由于你使用的是Scanner
,你可以nextInt()
就这样:
new Scanner(theStringWhichMightHaveANumber).nextInt();