Using a lot of IF statements within a FOR loop

Is there a simpler way to complete a task like this where I don't have to use a lot of IF statements.

for (int i = 0; i < registration.length(); i++) {
        char numberFromReg = registration.charAt(i);
        String yearFromReg = "";
        if (numberFromReg == '1') {
            yearFromReg += "1";
        }   else if (numberFromReg == '2') {
            yearFromReg += "2";
        }   else if (numberFromReg == '3') {
            yearFromReg += "3";
        }   else if (numberFromReg == '4') {
            yearFromReg += "4";
        }   else if (numberFromReg == '5') {
            yearFromReg += "5";
        }   else if (numberFromReg == '6') {
            yearFromReg += "6";
        }   else if (numberFromReg == '7') {
            yearFromReg += "7";
        }   else if (numberFromReg == '8') {
            yearFromReg += "8";
        }   else if (numberFromReg == '9') {
            yearFromReg += "9";
        }   else if (numberFromReg == '0') {
            yearFromReg += "0";
        }
    }
Jon Skeet
people
quotationmark

To solve the general case of more elegantly handling multiple if statements which all compare the same value, but to different constants, you'd normally use the switch statement. That would work in this case, but it would still be overkill IMO.

In this case, you're building up a string with all the digits from an input string. One option is to use a StringBuilder, and just append any digit, e.g.

StringBuilder builder = new StringBuilder();
for (int i = 0; i < registration.length(); i++) {
    char numberFromReg = registration.charAt(i);
    if (numberFromReg >= '0' && numberFromReg <= '9') {
        builder.append(numberFromReg);
    }
}
String yearFromReg = builder.toString();

(Yes, you could continue to use repeated string concatenation - using StringBuilder is more efficient and clearer though.)

Or you could use a regular expression to simply replace all non-digits with the empty string, effectively extracting all digits:

String yearFromReg = registration.replaceAll("\\D", "");

Or if your code readership isn't as familiar with regular expressions, equivalently:

String yearFromReg = registration.replaceAll("[^0-9]", "");

people

See more on this question at Stackoverflow