Dan*_*mer 2 java parseint java.util.scanner
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class MainProgram {
public static void main(String[] args ) throws IOException{
String seconds = " ";
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("/Users/mohammadmuntasir/Downloads/customersfile.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
boolean first = true;
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.next();
if (first == true){
seconds = s;
first = false;
}
}
}
System.out.println(Integer.parseInt(seconds)); // causes ERROR?
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试从单独位于第一行的文本文件中读取一个数字。我创建了一个名为 seconds 的整数,它将接收第一个数字并将被解析为一个整数。但我总是收到一个数字异常错误,而且我无法解析它。当我将 s 显示为字符串时,它会显示一个数字,旁边没有空格。谁能解释为什么会发生这种情况?
这是堆栈跟踪:
Exception in thread "main" java.lang.NumberFormatException: For input string: "300"
at java.lang.NumberFormatException.forInputString(NumberFormatE?xception.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at MainProgram.main(MainProgram.java:29)
Run Code Online (Sandbox Code Playgroud)
如果异常消息真的是这样的:
java.lang.NumberFormatException: For input string: "300"
Run Code Online (Sandbox Code Playgroud)
然后我们开始进入真正晦涩的原因。
这可能是同形文字的问题;即 Unicode 字符看起来像一个字符但实际上是不同的字符。
它可能是一个非打印字符。例如 ASCII NUL ... 或 Unicode BOM(字节顺序标记)字符。
我可以想到三种方法来诊断这个:
在调试器中运行您的代码并在 parseInt 方法上设置断点。然后查看您尝试解析的 String 对象,检查其长度(比如 N)和char字符数组中的前 N 个值。
使用文件工具以字节为单位检查文件。(在 UNIX / Linux / MacOSX 上,使用该od命令。)
添加一些代码以将字符串作为字符数组获取。对于每个数组条目,将 转换char为 anint并打印结果数字。
所有三种方法都应该告诉您字符串中的确切字符是什么,这应该可以解释为什么parseInt认为它们是错误的。
另一种可能是您错误地复制了异常消息。当您将其纳入问题时,堆栈跟踪有点混乱......
| 归档时间: |
|
| 查看次数: |
9118 次 |
| 最近记录: |