如何判断字符串是否为数值,实现指令数组元素的加法分支逻辑处理
实现方案
Java没有内置的字符串是否为有效整数的判断接口,最稳妥的实现是通过捕获Integer.parseInt()抛出的NumberFormatException做判断,可覆盖正负号、数值范围校验等所有边界场景。
步骤1:封装判断辅助方法
先实现独立的判断方法避免代码重复:
private static boolean isInteger(String s) { // 先判空避免空指针异常 if (s == null || s.isBlank()) { return false; } try { Integer.parseInt(s); return true; } catch (NumberFormatException e) { return false; } }
步骤2:修正原Add方法逻辑
注意原代码存在变量作用域问题:a和b定义在if代码块内部,外部return语句无法访问,需要提前在块外声明变量:
static int Add() { int a, b; Instindex++; if (isInteger(instructions[Instindex])) { a = Integer.parseInt(instructions[Instindex]); } else { ReadInstruction(); // 可根据业务需求补充ReadInstruction执行后的a赋值逻辑 } Instindex++; if (isInteger(instructions[Instindex])) { b = Integer.parseInt(instructions[Instindex]); } else { ReadInstruction(); // 可根据业务需求补充ReadInstruction执行后的b赋值逻辑 } return a + b; }
可选轻量实现:正则判断
如果你的场景只需要校验字符串由数字组成,不需要校验是否超出int范围,可以用正则实现,性能略高:
private static boolean isInteger(String s) { // 匹配可选负号 + 1个及以上数字 return s != null && s.matches("-?\\d+"); }
注意:正则实现不会校验数值是否超出int的最大/最小范围,比如字符串
"9999999999"超出int最大值2147483647,用正则判断会返回true,但调用Integer.parseInt()会抛出异常。
内容的提问来源于stack exchange,提问作者Adham El-sheikh
相关产品推荐
相关产品推荐

