简体   繁体   English

如何确定字符串是否等于Java中的数字范围?

[英]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]")
{
...
}
  1. You could try with regex like 您可以尝试使用正则表达式

     inputArray[2].matches("[0-9A-F]") 
  2. You could also use something like 您也可以使用类似

     inputArray[2].length()==1 && "0123456789ABCDEF".condains(inputArray[2]) 
  3. 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-9AF等指定范围内

     ('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.

相关问题 如何使用Arrays.equals确定2个2d阵列是否相同(意味着它们具有相同的数字但不是相同的顺序)? 在JAVA - How do i determine if 2 2d arrays are identical(meaning they have the same numbers but not same order)w/o using Arrays.equals? in JAVA 如何获取名称等于Java中的方法和字符串的输入隐藏字段的数据 - How can i get the data of the input hidden field whose name equals to a method and a string in java 如何在Java中的字符串中的空格之间导出数字? - How can I export numbers between spaces in a string in Java? 检查字符串在数字范围内Java - Check String is in a range of numbers Java 确定一个字符串中有多少个数字 - Determine how many numbers in a string 如何确定java中数字的倍数 - how to determine the multiples of numbers in java 我如何检查 char 是否等于某个字符串 - How can i check if char equals some string 如何在Java中的equals覆盖方法中强制转换对象? - How can I cast an Object in an equals override method in Java? 如何点击 Recycler View 并使用 equals 进行扫描? - Java - How can I make a click for Recycler View and scan with equals? - Java 如何强制某个属性等于其中一个常量值(在Java中)? - How can I enforce that an attribute equals one of the constant values (in Java)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM