NumberFormatException通常是由于字符串无法转换为数字而引起的异常。为了正确处理NumberFormatException,可以考虑以下几个方法:
使用try-catch语句捕获异常:在可能发生NumberFormatException的代码块中使用try-catch语句捕获异常,并在catch块中处理异常情况。try { int num = Integer.parseInt(str);} catch (NumberFormatException e) { System.out.println("输入的字符串无法转换为数字");}使用正则表达式验证输入:在将字符串转换为数字之前,可以使用正则表达式验证输入是否为数字。if (str.matches("\\d+")) { int num = Integer.parseInt(str);} else { System.out.println("输入的字符串不是数字");}使用tryParse方法:如果不想抛出异常而是希望安全地转换字符串为数字,可以使用自定义的tryParse方法。public static Integer tryParse(String str) { try { return Integer.parseInt(str); } catch (NumberFormatException e) { return null; }}Integer num = tryParse(str);if (num != null) { System.out.println("转换成功:" + num);} else { System.out.println("输入的字符串无法转换为数字");}通过以上方法,可以正确处理NumberFormatException异常,避免程序因为无法转换字符串为数字而出现异常情况。