【问题标题】:Java Input of 5 Numbers, 'Regex' and 'Else if'5 个数字的 Java 输入,“Regex”和“Else if”
【发布时间】:2013-11-03 01:06:48
【问题描述】:

我已经修复了我之前的代码问题,现在我希望它通过“Else if”识别它是 4 位及以下还是 6 位及以上。

当我输入字母以在“Else if”中使用 System.out.println 来拒绝它时。

  String digit;
  String regex;
  String regex1;
  regex = "[0-9]{5}";
  String test;
  String validLength = "5";
  char one, two, three, four, five; {
   System.out.println("In this game, you will have to input 5 digits.");
   do {
    System.out.println("Please input 5-digits.");
    digit = console.next();
    test = digit.replaceAll("[a-zA-Z]", "");
    if (digit.matches(regex)) {
     one = (char) digit.charAt(0);
     two = (char) digit.charAt(1);
     three = (char) digit.charAt(2);
     four = (char) digit.charAt(3);
     five = (char) digit.charAt(4);
     System.out.println((one + two + three + four + five) / 2);
    }

【问题讨论】:

  • 考虑将该值与9999100000 进行比较。
  • 我希望它能够知道它是 4 位数字还是 5 位数字等。但也能够接受 00001,因为它是 5 位数字,因此我正在尝试使用正则表达式我不太熟悉。
  • 您的某些else if 语句后面有分号。删除那些以防止没有 ifs 的 else 的编译时错误。您的代码看起来不错,只是 lengthString 的方法,而不是字段。所以它必须是digit.length()
  • 我删除了分号,但问题仍然存在。我将研究长度方法并用另一个脚本回归。
  • 正则表达式应该是:regex = "[0-9]{5}";不是 regex = "[0-9](5)";

标签: java regex digits


【解决方案1】:

这个正则表达式应该符合您的需要(带有前导零):

[0-9]{5}

你将使用一个while循环,循环直到满足这两个条件,就像

while (!inputString.matches("[0-9]{5}")) {
    // ask again and again
    if (!isInteger(inputString)) {
        // invalid input
    } else {
        if (inputString.length() < 5) {
            // too low
        } else if (inputString.length() > 5) {
            // too high
        }
    }     
}

你可以使用这样的辅助方法:

public boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    }
    return true;
}

【讨论】:

  • 感谢您,我修复了大部分代码。 ;) 但我仍然想知道他们是否可以识别 5 位数字中的字母。我试过else if (digit.matches(regex1) &amp;&amp; digit.matches(regex));,其中regex1 = [a-zA-Z]{5}regex = [0-9]{5}
  • 如果您的字符串包含任何字母字符,此正则表达式将匹配:.*[a-zA-Z]+.*
  • 上面的代码有什么问题?我还希望它是字母数字的混合体,并且仍然能够识别。
  • 其中一个错误是test = Integer.parseInt(digit); 行,如果它无法解析该字符串,则 parseInt 方法会抛出一个异常,因此如果您不处理该异常,则该方法的其余部分不会被执行。之后你就不再使用这个test 变量了。
  • 如果您想识别包含字母的数字,您可以从字符串中删除非数字字符,如下所示:stackoverflow.com/questions/10372862/…Google 是您的朋友。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-17
  • 2022-01-19
  • 1970-01-01
  • 2021-12-10
  • 2015-10-19
  • 2014-04-27
相关资源
最近更新 更多