Question

I've fixed my previous issues with the code, now i want it to recognize if it's 4 digits and less or 6 digits and above with an "Else if".

And when i input letters to deny it with a System.out.println within an "Else if" as well.

  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);
    }
Was it helpful?

Solution

This regex should match your need (with leading zeros):

[0-9]{5}

and you will use a while loop, looping until these two conditions are met, something like

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

And you can use a helper method like this:

public boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    }
    return true;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top