2015-08-08 59 views
0

我是.net开发人员,刚开始使用Java开发。目标虚拟机发生异常:对于输入字符串:“1”java.lang.NumberFormatException

br = new BufferedReader(new FileReader(filePath)); 
while ((sCurrentLine = br.readLine()) != null) { 
    int vertIdx = sCurrentLine.trim().indexOf(space); 
    String ver = sCurrentLine.trim().substring(0,vertIdx); 
    int vrtInt = Integer.parseInt(ver.trim()); // Here is the error 
    //Code Continues 
} 

在的Integer.parseInt(ver.trim()),我收到以下异常:

Exception occurred in target VM: For input string: "1" 
java.lang.NumberFormatException: For input string: "1" 
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 
    at java.lang.Integer.parseInt(Integer.java:580) 
    at java.lang.Integer.parseInt(Integer.java:615) 
    at kosaraju.Graph.createGraph(Graph.java:75) 
    at kosaraju.Graph.main(Graph.java:247) 

此时执行的,我对sCurretline值为 “1 4” 和版本是“1” 我无法弄清楚这样一个小问题。有人可以指出我的代码中的错误吗?

这里是我的观察窗口:

enter image description here

+0

请勿张贴在引号中的例外。使用代码块(编辑器上的“{}”按钮)来保存其格式。也请缩进您的代码,以便更容易阅读并查看其片段的范围。 – Pshemo

+0

你确定在你想分析的字符串中没有不可打印的字符吗?尝试打印每个字符(或最好是它的代码点)像'System.out.println(Arrays.toString(yourString.chars()。toArray()));' – Pshemo

+0

我得到这个在调试输出窗口:[65279,49] 。我的字符串的值为1 – PushCode

回答

2

基于结果[65279, 49]它看起来像你的文字与Zero Width No-Break Space,因为它不被视为空白不能修剪,也不解析为数字开始。

您需要将其删除,例如使用replaceAll("[^\\d+-]","")将删除任何不是digit,+-的字符。

+0

它工作。但是,请你解释一下这个问题。我不会在c#代码中进行这些替换,而我今天刚刚开始使用Java。 – PushCode

+0

@PushCode我不是C#开发人员,所以我不能告诉你为什么'trim()'还有删除非断点空格,但似乎Java不会将它们作为可以通过'trim()'删除的白字符。我不知道我还能说什么。如果你需要更多关于'replaceAll(“[^ \\ d + - ]”,“”)'的信息,那么它就是允许我们为正则表达式找到匹配的方法,并用其他东西替换它(在我们的例子中用空字符串,这意味着我们正在删除匹配的部分)。 – Pshemo

0

您需要删除字符蒙山.replaceAll( “[^ 0-9]”, “”)

br = new BufferedReader(new FileReader(filePath)); 
 
while ((sCurrentLine = br.readLine()) != null) { 
 
    int vertIdx = sCurrentLine.trim().indexOf(space); 
 
    String ver = sCurrentLine.trim().substring(0,vertIdx); 
 
    ver=ver.replaceAll("[^0-9]", ""); 
 
    int vrtInt = Integer.parseInt(ver.trim()); // Here is the error 
 
    //Code Continues 
 
}

相关问题