如何在Java中从字符串中设置整数和字符串范围

huangapple go评论146阅读模式
英文:

How to set integer and string range from string in Java

问题

给定的输入是 Integer + String,但我想设置整数输入范围为 1~34 和字符串范围为 A~F。

如果我这样做,

int i = (Integer.parseInt(input));

if (n > 34) {
    System.out.println("number too high");
}

它会给我报错:

Exception in thread "main" java.lang.NumberFormatException: For input string: "35A"

有没有办法让它工作?提前感谢您的帮助 如何在Java中从字符串中设置整数和字符串范围

如果字符串是从 1A 到 34F,它应该通过,超出这个范围的应该失败... 请帮忙!

英文:

The input given is Integer + String, however I want to set a range of integer input (1~34) and String (A~F).
if I do,

int i = (Integer.parseInt(input));

if (n > 34) {
    System.out.println("number too high");
}

it gives me

Exception in thread "main" java.lang.NumberFormatException: For input string: "35A"

is there any way to make this work? thanks in advace 如何在Java中从字符串中设置整数和字符串范围

if the string is 1A to 34F it should pass, anything over that should fail.. please help!

答案1

得分: 0

如果您要解析十六进制字符串,请传递一个基数参数:

Integer.parseInt(input, 16)

如果不是十六进制,您需要首先将字符串分成数字部分和其他部分(无法告诉您如何分割,因为您还没有告诉我们选项是什么),然后只将包含数字的字符串传递给Integer.parseInt

英文:

If you are trying to parse a hexadecimal string, pass a radix argument:

Integer.parseInt(input, 16)

If it's not hexadecimal, you need to separate the String into the number part and other part first (can't tell you how since you haven't told us what the options are), and then only pass the String containing numbers to Integer.parseInt.

答案2

得分: 0

你可以首先将字符串分割为数字和字母部分:

String[] split = n.split("(?=[A-Z])");

然后检查这两部分是否符合你的需求:

if (Integer.parseInt(split[0]) > 34 || split[1].charAt(0) > 'F') {
    System.out.println("数字太大");
}

你需要在此之前检查你的字符串是否实际符合该模式,但是你在评论中提到它总是以这种格式出现,所以应该可以工作。如果小写字母也可能出现,你需要更改正则表达式和条件,或者简单地在输入字符串上调用toUppercase()方法。

英文:

You could first split the String into number and letter

String[] split = n.split("(?=[A-Z])");

then check if the two parts fit your needs

if(Integer.parseInt(split[0]) > 34 || split[1].charAt(0) > 'F') {
    System.out.println("number too high");
}

You'd have to check beforehand that your String actually conforms to that pattern but you said in the comments that it's always in that format, so it should work. Also if lowercase letters are possible you have to change the regex and condition or simply call toUppercase() on the input String.

答案3

得分: 0

以下是翻译好的内容:

我正在使用正则表达式来解决问题

String patternString = "(0{0,1}[1-9][A-F])|([1-2]{1}\\d{1}[A-F]{1})|(3{1}[0-4]{1}[A-F]{1})";
String data[] = {"34f", "00F", "01F", "1a", "1A", "26b"};

for (int i = 0; i < data.length; i++) {
    System.out.println(data[i] + ":" + Pattern.matches(patternString, data[i]));
}

// 期望结果:
// 34f:false
// 00F:false
// 01F:true
// 1a:false
// 1A:true
// 26b:false
英文:

I am using the regular expression to solve the problem:

 String patternString=&quot;(0{0,1}[1-9][A-F])|([1-2]{1}\\d{1}[A-F]{1})|(3{1}[0-4]{1}[A-F]{1})&quot;;
    String data[]={&quot;34f&quot;,&quot;00F&quot;,&quot;01F&quot;,&quot;1a&quot;,&quot;1A&quot;,&quot;26b&quot;};
    
    for (int i=0;i &lt; data.length;i++){
        System.out.println(data[i]+&quot;:&quot;+Pattern.matches(patternString, data[i]));
    }

 //expected result&quot;
 //34f:false
 //00F:false
 //01F:true
 //1a:false
 //1A:true
 //26b:false

答案4

得分: 0

我建议你使用正则表达式。

boolean result2 = Pattern.matches("[0-3][0-4]?[A-F]", "34A"); // 编译并匹配模式

System.out.println(result2);

这个模式将满足你的要求。

英文:

I would recommend you to use regex.

boolean result2 = Pattern.matches(&quot;[0-3][0-4]?[A-F]&quot;, &quot;34A&quot;); // Compiles and matches pattern

System.out.println(result2);

This pattern will fulfill your requirement.

答案5

得分: 0

你可以使用正则表达式的分组功能来轻松从字符串中提取数据:

public class RandomStuff {

  public static void main(String[] args) {
    String string = "34F";
    Pattern pattern = Pattern.compile("(\\d{1,2})([A-F])");
    Matcher matcher = pattern.matcher(string);
    if (!matcher.find()) {
      System.out.println("不匹配模式,执行必要的操作");
      // 根据使用情况停止执行
    }
    int number = Integer.parseInt(matcher.group(1));
    if (number < 1 || number > 34) {
      System.out.println("数字不在范围内");//或其他消息
    }
    // 无需验证字母
  }
}

(\\d{1,2}) - 匹配1或2个数字(0到99),并将其捕获为第1组。

([A-F]) 匹配单个字母(A、B、C、D、E或F),并将结果捕获为第2组。如果小写字母也有效,您可以为此组添加不区分大小写标志或添加小写字母字符集 - [a-f]

英文:

You can use regex with grouping to easily extract data from the string:

public class RandomStuff {

  public static void main(String[] args) {
    String string = &quot;34F&quot;;
    Pattern pattern = Pattern.compile(&quot;(\\d{1,2})([A-F])&quot;);
    Matcher matcher = pattern.matcher(string);
    if (!matcher.find()) {
      System.out.println(&quot;does not match pattern, do whatever is needed&quot;);
      //stop execution however applicable for use case
    }
    int number = Integer.parseInt(matcher.group(1));
    if (number &lt; 1 || number &gt; 34) {
      System.out.println(&quot;number not in range&quot;);//or other message
    }
    // no need to validate letters
  }
}

(\\d{1,2}) - matches 1 or 2 numbers (0 to 99) and captures it as group 1.

([A-F]) matches a single letter (A, B, C, D, E or F) and captures result as group 2. If lower case letters are valid as well, you can add a case insensitive flag or add character set for lower letters as well - [a-f], to this group.

答案6

得分: 0

检查最后一个字符。当 parseInt 出现异常且没有最后一个字符时,可以捕获 NumberFormatException。

String input = "34F";
char lastc = input.charAt(input.length()-1);

if(lastc >= 'A' && lastc <= 'F'){
    try{
        int n = (Integer.parseInt(input.substring(0,input.length()-1)));

        if (n > 34 || n < 1) {
            System.out.println("数字不在范围内");
        }
    } catch(NumberFormatException e1){
        System.err.println("输入错误,请检查。");
    }
}else{
    System.err.println("输入错误,请检查。");
}
英文:

Check the last character.And you can catch NumberFormatException when the parseInt gets an exception without last character.

    String input = &quot;34F&quot;;
    char lastc = input.charAt(input.length()-1);

    if(lastc &gt;= &#39;A&#39; &amp;&amp; lastc &lt;= &#39;F&#39;){
        try{
            int n = (Integer.parseInt(input.substring(0,input.length()-1)));

            if (n &gt; 34 || n &lt; 1) {
                System.out.println(&quot;number not in range&quot;);
            }
        } catch(NumberFormatException e1){
            System.err.println(&quot;input error.check it.&quot;);
        }
    }else{
        System.err.println(&quot;input error.check it.&quot;);
    }

huangapple
  • 本文由 发表于 2023年6月19日 16:12:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76504782.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定