Java 输入 5 个数字, 'Regex' 和 'Else if'

标签 java regex digits

我已经解决了之前的代码问题,现在我希望它能够通过“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);
    }

最佳答案

此正则表达式应满足您的需求(带前导零):

[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;
}

关于Java 输入 5 个数字, 'Regex' 和 'Else if',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19748769/

相关文章:

python - 我没有得到匹配的字符串

python - 正则表达式返回两个字符串之间的所有字符

java - 从字符串中获取第二大数字的函数

haskell - 如何显示更多的haskell pi 数字?

java - 使用按钮将文件添加到 JList

java - 在spring boot中使用openapi使用@Schema(allowableValues=)作为枚举参数

java - Android Tooltip 菜单项样式

java - Getter 和 Setter 方法以及读取 txt 文件

java - 我将如何在 Java 中拆分一个句子

python - np.convolve 与 10**9 有什么问题?