我有一个字符串,想要从中解析出一个整数,但却遇到了运行时异常。我知道当parseNUMBERTYPE函数被应用于不适当定义的字符串时会触发该异常,而空格或字母在代码期望数字的位置上出现也会导致该异常。然而,我使用的测试字符串只是数字5,据我所知没有其他任何东西。针对其他用户的NumberFormatException问题,我看到了几个建议,在解析之前应用trim()函数,但尝试过后仍然没有成功。
我还尝试用简单的、未存储的值“5”来替换要解析的字符串。这与程序报告的相关变量存储的字符串值相同,但是虽然解析该变量会失败并显示本帖子中所说的异常,但未存储的值似乎可以完美地代替它。
请注意,该字符串变量是由文件扫描器读取的。我必须认为我的问题与未知、不需要的“隐形”字符有关,这些字符除了数字五外还被读取,但我无法确定为什么会发生这种情况,也不知道如何停止它。该文件格式为 .txt
以下是我的代码:
我还尝试用简单的、未存储的值“5”来替换要解析的字符串。这与程序报告的相关变量存储的字符串值相同,但是虽然解析该变量会失败并显示本帖子中所说的异常,但未存储的值似乎可以完美地代替它。
请注意,该字符串变量是由文件扫描器读取的。我必须认为我的问题与未知、不需要的“隐形”字符有关,这些字符除了数字五外还被读取,但我无法确定为什么会发生这种情况,也不知道如何停止它。该文件格式为 .txt
以下是我的代码:
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the file name:");
String filename = scan.nextLine();
File tempfile = new File(filename);
Scanner filereader = new Scanner(tempfile);
//this is meant to assign to the String line1 the numerical value (5)
//of the file's first line
String line1 = filereader.nextLine();
//this was added later to determine if line1 held the value I expect
//it outputs the single digit 5, as expected and appropriate
System.out.println(line1);
//this was added to test how flawed my system was
//it runs fine, indicating to me that the problem may in my reader
int num2 = Integer.parseInt("5");
//this is where the exception is cast
int num1 = Integer.parseInt(line1);
我看到了以下错误信息:
Exception in thread "main" java.lang.NumberFormatException: For input string: "5"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at Driver.main(Driver.java:26)
非常感谢您的帮助。
根据迄今为止给出的建议,代码已被修改为如下所示:
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the file name:");
String filename=scan.nextLine();
File tempfile = new File(filename);
Scanner filereader = new Scanner(tempfile);
//this is meant to assign the String line1 the numerical value (5)
//of the file's first line
String line1 = filereader.nextLine();
//this was added after to determine if line1 held the value I expect
//it outputs the single digit 5, as expected and appropriate
System.out.println("["+line1+"]");
//this was added to test how flawed my system was
//it runs fine, indicating to me that the problem is in my reader
int num2 = Integer.parseInt("5");
//this is where the exception is cast
int num1 = Integer.parseInt(line1.trim());
如果我有什么误解您的指导,请纠正我。目前问题仍然存在,出现了相同的错误报告。
Integer.parseInt(line1.trim());
。该代码可将字符串转换为整数类型,并且通过去除前后空格来保证输入格式的正确性。 - Rohit Jainline1.toCharArray().length
来验证 "5" 的长度是否真的是一个字符吗? - bdkosherecho 5 >x
,然后按回车键。这将在Windows上创建一个干净的文件... - ppeterka