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

Neh*_*aje 1 java

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

String nop = no_of_people.getText().toString();
System.out.println(nop);
int nop1 = Integer.parseInt(nop);
System.out.println(nop1);
Run Code Online (Sandbox Code Playgroud)

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

npi*_*nti 6

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

如果您想避免此类问题,我建议您使用格式化文本字段微调器.

后面的选项将保证您具有数值,并且应该避免使用try catch块.