【问题标题】:How to check if a string is a numeric or not for example "1" is but "x" is not如何检查字符串是否为数字,例如“1”是但“x”不是
【发布时间】:2021-08-14 15:47:58
【问题描述】:
static int Add() {
  Instindex++;
  if ()

    int a = Integer.parseInt(instructions[Instindex]);
  else
    ReadInstruction();
  Instindex++;
  if (x == (int) x)
    int b = Integer.parseInt(instructions[Instindex]);
  else
    ReadInstruction();
  return a + b;
}

instindex 是指令数组的索引,它是已解析程序的数组我想检查我在其索引处的元素是否是数字,以便我可以正常执行添加,否则我将调用我的系统调用者

【问题讨论】:

  • 那么,Integer.parseInt 没有告诉你“x”不是数字吗?
  • Integer.parseInt 告诉我,但如果它不是数字,则会导致异常
  • 那你为什么不做一个方法,它捕获异常并返回false,如果没有抛出异常则返回true?
  • 强调——异常并不总是意味着您的代码中有错误。例外是要使用的工具。

标签: java operating-system


【解决方案1】:

你可以这样检查:

boolean isNumeric(String str){
    try{
        Integer.parseInt(str);
        return true;
    }catch (NumberFormatException e){
        return false;
    }
}

【讨论】:

    【解决方案2】:
    public static boolean isNumeric(String str) {
      return str.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.
    }
    

    试试这个

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-27
      相关资源
      最近更新 更多