首页 > 解决方案 > 检查字符串输入的任何部分是否不是数字

问题描述

我在Java中找不到这个答案,所以我会在这里问。我需要检查字符串输入的 3 部分是否包含数字(int)。

输入将是 HOURS:MINUTES:SECONDS(例如 10:40:50,即 10 小时 40 分钟和 50 秒)。到目前为止,我通过将 String[] 中的值拆分为一个数组:。我已将字符串解析为整数,并使用 if 语句检查所有 3 个部分是否等于或大于 0。问题是,如果我现在使用字母,我只会得到一个错误,但我想检查是否3 个部分中的任何一个都包含一个不是 0-9 的字符,但不知道如何。

首先,我认为这样的事情可以工作,但真的不行。

String[] inputString = input.split(":");

if(inputString.length == 3) {
  String[] alphabet = {"a","b","c"};
  if(ArrayUtils.contains(alphabet,input)){
    gives error message
  }
  int hoursInt = Integer.parseInt(inputString[0]);
  int minutesInt = Integer.parseInt(inputString[1]);
  int secondsInt = Integer.parseInt(inputString[2]);
  else if(hoursInt >= 0 || minutesInt >= 0 || secondsInt >= 0) {
    successfull
  }
  else {
    gives error message
  }
else {
  gives error message
}

最后,我只想检查这三个部分中的任何一个是否包含一个字符,如果没有,运行一些东西。

标签: java

解决方案


如果您确定总是必须解析String表单/模式HH:mm:ss
的 a (描述一天中的某个时间),

您可以尝试将其解析为 a LocalTime,这仅在 partHH和实际上是有效整数mm有效时间值时才有效。ss

这样做可能会发现Exception输入错误String

public static void main(String[] arguments) {
    String input = "10:40:50";
    String wrongInput = "ab:cd:ef";
    LocalTime time = LocalTime.parse(input);
    System.out.println(time.format(DateTimeFormatter.ISO_LOCAL_TIME));

    try {
        LocalTime t = LocalTime.parse(wrongInput);
    } catch (DateTimeParseException dtpE) {
        System.err.println("Input not parseable...");
        dtpE.printStackTrace();
    }
}

这个最小示例的输出是

10:40:50
Input not parseable...
java.time.format.DateTimeParseException: Text 'ab:cd:ef' could not be parsed at index 0
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalTime.parse(LocalTime.java:441)
    at java.time.LocalTime.parse(LocalTime.java:426)
    at de.os.prodefacto.StackoverflowDemo.main(StackoverflowDemo.java:120)

推荐阅读