[英]How can I determine if a String equals a range of numbers in Java?
I receive input from the user that can be anything ranging from "0", "1", "2"... "F", "?", etc., and store this in a String. 我收到用户的输入,输入范围可以是“ 0”,“ 1”,“ 2” ...“ F”,“?”等,并将其存储在字符串中。
How can I determine if what is stored in the string is a value from 1 to 8, without using 8 if statements? 如何在不使用8 if语句的情况下确定字符串中存储的值是1到8之间的值?
It would look something like: 它看起来像:
String[] inputArray = new String[3];
if (inputArray[2] == "[1 through 8]")
{
...
}
You could try with regex like 您可以尝试使用正则表达式
inputArray[2].matches("[0-9A-F]")
You could also use something like 您也可以使用类似
inputArray[2].length()==1 && "0123456789ABCDEF".condains(inputArray[2])
Or read first character via char ch = inputArray[2].charAt(0)
(also make sure that inputArray[2]
contains only one character) and see if it is in specified range 0-9
or AF
like 或通过char ch = inputArray[2].charAt(0)
读取第一个字符(还要确保inputArray[2]
仅包含一个字符),并查看其是否在0-9
或AF
等指定范围内
('0'<=ch && ch<='9') || ('A'<=ch && ch<='F')
As @user2864740 already suggested, using regular expressions would be the best solution. 正如@ user2864740已经建议的那样,使用正则表达式将是最佳解决方案。
http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
Here you have the Java API for Regex in particular Pattern 在这里,您具有用于特定模式的Regex的Java API
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
This example shows how Patterns should be used. 本示例说明了如何使用模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.