mardi 29 septembre 2015

Avoid 26 if/elseif/else statements when checking for a letter in user input

I was just wondering if there was a simple way to check for the value of a letter from user input. For example,

Scanner scanner = new Scanner(System.in);
String message = scanner.nextLine();
String letter;
int length = message.length();
for(int i = 0; i < length; i++){
    letter = message.substring(i,i+1);
    if(letter.equalsIgnoreCase("a")){
        System.out.println("letter a");
        //of course the real program won't just print out "letter a" but this is to show that all actions are different) 
    }else if(letter.equalsIgnoreCase("b"){
        System.out.println("letter b");
    }etc... for all of the possible values of "letter" 
} 

Is there any way to write the above statement without having to make 26+ if/else statements? (I know there's switch-case but you'd still have to write 26+ of them). Any help is greatly appreciated!

Sorry for any formatting errors as I am on my phone currently.

Aucun commentaire:

Enregistrer un commentaire