java - 检查字符串输入的任何部分是否不是数字
问题描述
我在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
}
最后,我只想检查这三个部分中的任何一个是否包含一个字符,如果没有,运行一些东西。
解决方案
如果您确定总是必须解析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)
推荐阅读
- javascript - 多次调用reactjs组件
- google-apps-script - 如何使用 Stackdriver Logging API 获取日志
- javascript - 如何对以 const 和一堆 var 开头的 JavaScript 进行非混淆处理
- python - 使用 Selenium 向下滚动直到不可见元素变为可见
- python-3.x - 如何打印某个整数返回的次数之和?
- python - Python 诅咒 update_panels() 和 Panel.move() 问题
- python - 词向量的 np.average
- arrays - 删除第一列值重复的二维数组的元素(Swift)
- mysql - 如何将 QT 5.14.1 连接到 MYSQL 数据库?
- android - react-native hello world app - 在模拟器中工作但不在物理设备中