简体   繁体   中英

Java: NumberFormatException in converting string to integer

I want to retrieve value from textbox and convert it to integer. I wrote the following code but it throws a 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.println prints me the number but converting to integer gives an exception. What am I doing wrong?

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 .trim method or else, do a replace all using the .replaceAll("\\\\s+", "") .

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

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

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.

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

Try this:

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

I would suggest replacing all non-digit characters from String first converting to 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM