Java:将字符串转换为整数时的 NumberFormatException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10630892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:54:24  来源:igfitidea点击:

Java: NumberFormatException in converting string to integer

java

提问by Neha Raje

I want to retrieve value from textbox and convert it to integer. I wrote the following code but it throws a NumberFormatException.

我想从文本框中检索值并将其转换为整数。我写了下面的代码,但它抛出一个NumberFormatException.

String nop = no_of_people.getText().toString();
System.out.println(nop);
int nop1 = Integer.parseInt(nop);
System.out.println(nop1);

The first call to System.out.printlnprints me the number but converting to integer gives an exception. What am I doing wrong?

第一次调用System.out.println打印数字但转换为整数给出了一个例外。我究竟做错了什么?

回答by npinti

Note that the parsing will fail if there are any white spaces in your string. You could either trim the string first by using the .trimmethod or else, do a replace all using the .replaceAll("\\s+", "").

请注意,如果您的字符串中有任何空格,解析将失败。您可以先使用.trim方法修剪字符串,或者使用.replaceAll("\\s+", "").

If you want to avoid such issues, I would recommend you use a Formatted Text Fieldor a Spinner.

如果您想避免此类问题,我建议您使用Formatted Text FieldSpinner

The latter options will guarantee that you have numeric values and should avoid you the need of using try catch blocks.

后一个选项将保证您拥有数值并且应该避免您需要使用 try catch 块。

回答by Lucifer

Your TextBox may contain number with a white space. Try following edited code. You need to trim the TextBox Value before converting it to Integer. Also make sure that value is not exceeding to integer range.

您的 TextBox 可能包含带有空格的数字。尝试遵循编辑过的代码。在将其转换为整数之前,您需要修剪 TextBox 值。还要确保该值不超过整数范围。

String nop=(no_of_people.getText().toString().trim());
System.out.println(nop);
int nop1 = Integer.parseInt(nop);
System.out.println(nop1);

回答by Anuj Balan

Try this:

试试这个:

int nop1 = Integer.parseInt(no_of_people.getText().toString().trim());
System.out.println(nop1);

回答by anubhava

I would suggest replacing all non-digit charactersfrom String first converting to int:

我建议non-digit characters先将 String 中的所有内容替换为int

replaceAll("\D+", "");

You can use this code:

您可以使用此代码:

String nop=(no_of_people.getText().toString().replaceAll("\D+", ""));
System.out.printf("nop=[%s]%n", nop);
int nop1 = Integer.parseInt(nop);
System.out.printf("nop1=[%d]%n", nop1);