给定一个包含小整数的输入String的NumberFormatException [英] NumberFormatException given an input String holding a small integer

查看:94
本文介绍了给定一个包含小整数的输入String的NumberFormatException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个String,我想从中解析一个整数,并且找不到解决此运行时异常的方法.我知道,这是为了在将parseNUMBERTYPE函数应用于不正确定义的String时显示,并且代码期望数字所在的空格或字母会触发它.但是,据我所知,我用作测试虚拟字符串的String只是简单地告诉了数字5.我已经看到一些建议,以应对其他用户的NumberFormatException问题,提倡在解析之前应用trim()函数,尝试过但没有成功.

I have a String from which I would like to parse an integer and cannot find a way past this runtime exception. I understand that it is meant to display at times when a parseNUMBERTYPE function is applied to an inappropriately defined String, and that blank spaces or letters where the code expects numbers to be can trigger it. However, the String I am using as a test dummy is as far as I can tell simply the numeral 5. I have seen several suggestions in response to other users' NumberFormatException problems advocating the application of a trim() function before parsing, and I have tried this with no success.

我还尝试用简单的未存储值"5"替换我想解析的字符串.这与程序似乎报告为相关变量的已存储String值的结果相同,但是虽然由于该帖子的同名异常而使该变量解析失败,但未存储的值似乎在其位置上运行得很好.

I have also tried replacing the String I wish to parse with the simple, unstored value "5". This is the same as what the program seems to report as the relevant variable's stored String value, but while parsing that variable fails with this post's eponymous exception, the unstored value appears to run perfectly well in its place.

请注意,文件扫描程序将读取String变量.我必须假定我的问题与除了数字5之外正在读取的未知的,不需要的,不可见的"字符有关,但我无法确定为什么会这样或如何停止它.该文件的格式为.txt

Note that the String variable is read by a File Scanner. I must suppose my problem has something to do with unknown, unwanted, 'invisible' characters that are being read in addition to the number five, but I cannot determine why this is happening or how to stop it. The file is formatted as .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)

感谢您的帮助.

为响应到目前为止给出的建议,已将代码修改为如下所示:

In response to the suggestions given so far, the code has been modified to appear as follows:

    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());

如果我以某种方式误解了您的指导,请纠正我.从目前的情况来看,问题仍然存在,并且有相同的错误报告.

Please correct me if I have misinterpreted your guidance in some way. As it stands, the problem persists, with an identical error report.

推荐答案

查看异常中的消息,它表明字符串中没有其他可见字符或空格,因为5用引号引起来(并且对Java源代码的检查显示,此处打印的消息在用引号引起来的字符串包围之前似乎并未修改为删除空格.

Looking at the message in the exception, it shows that there are no additional visible characters or whitespace in the string since the 5 is surrounded by quotes (and a quick check of the Java source code shows that the message printed here does not appear to be modified to remove whitespace before surrounding the string with quotes).

这意味着您的字符串中包含隐藏的非打印字符,或者5本身实际上根本不是5,而是来自另一种类似于5的语言的unicode字符.

This means that either there are hidden non-printing characters in your string, or the 5 itself is actually not a 5 at all, and is instead some unicode character from another language that resembles a 5.

解决这个问题的简单调试方式是打印字符串的长度,因为这样可以快速找出其中是否还有其他隐藏字符.

Simple debug case to sort this out would be to print the length of your string, as this will quickly sort out whether there are additional hidden characters in it.

System.out.println("String: [" + line1 + "] size: " + line1.size());

在那之后,如果这是期望的行为,则可以使用正则表达式来获取连续的第一组数字:

After that, a regex can be used to get the first consecutive set of digits, if that is the desired behaviour:

    Pattern pattern = Pattern.compile("(\\d+)");
    Matcher matcher = pattern.matcher(line1);
    if (matcher.find())
    {
        String digits = matcher.group();
        int num = Integer.parseInt(digits);
    }

或者,如果有可能或希望删除数字之间的字符,则可以使用replaceAll:

Alternatively, if it is possible or desired to remove characters in between digits then a replaceAll can be used:

 String digits = line1.replaceAll("[^0-9]","");

对于字符串"5 6",第一个方法将给您5,第二个方法将给您56.

For the string "5 6", the first method will give you 5, and the second will give you 56.

这篇关于给定一个包含小整数的输入String的NumberFormatException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆