关于Exception in thread "main" java.lang.NumberFormatException: For input string: " 1 "的原因和解决方法

运行这段程序

public class test {
	public static void main(String [] args) {
		String a=" 1 ";
		int b=Integer.parseInt(a);
		System.out.printf("%d",b);
	}
}

终端会报出错误:
Exception in thread “main” java.lang.NumberFormatException: For input string: " 1 "
at
java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:644)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at test.main(test.java:4)

原因

第四行的数制转换出现了问题,注意观察第三行需要转换的字符串前后含有空格,所以Integer.parseInt(a)报错。

Integer.parseInt(a);

改为

Integer.parseInt(a.trim());

trim()函数的作用是去除字符串前后多余的空格。

修改后的代码

public class test {
	public static void main(String [] args) {
		String a=" 1 ";
		int b=Integer.parseInt(a.trim());
		System.out.printf("%d",b);
	}
}

运行结果:1

  • 8
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用\[1\]中提到,"错误关键字java.lang.NumberFormatException"明确告诉我们这是一个数字格式异常。而引用\[2\]中指出,在进行进制转换时,使用Integer.parseInt()等方法时需要注意去掉需要转换的数字的进制标志位。因此,根据你提供的错误信息"Exception in thread "main" java.lang.NumberFormatException: For input string: "",可以推断出你在进行数字转换时,输入的字符串为空字符串,导致了数字格式异常。为了解决这个问题,你需要确保输入的字符串不为空,并且符合正确的数字格式。 #### 引用[.reference_title] - *1* [java.lang.NumberFormatException 错误及解决办法](https://blog.csdn.net/xiaodongvtion/article/details/8835668)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Exception in threadmainjava.lang.NumberFormatException: For input string: “XXXX“](https://blog.csdn.net/qq_48666555/article/details/123585704)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值