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


i wondering if there simple way check value of letter user input. example,

scanner scanner = new scanner(system.in); string message = scanner.nextline(); string letter; int length = message.length(); (int i=0; < length; i++) {     letter = message.substring(i, i+1);     if (letter.equalsignorecase("a")) {         system.out.println("letter a");         // of course real program won't print out "letter a"         // show actions different     } else if(letter.equalsignorecase("b") {         system.out.println("letter b");     } // etc... of possible values of "letter" } 

is there way write above statement without having make 26+ if/else statements? (i know there's switch-case you'd still have write 26+ of them). appreciated!

well, according comments printing different text depending on letter. in case, tim's idea of using map pretty good. show basic example:


in class, create hashmap. i'm guessing final static 1 fine:

private static final hashmap<string, string> messages = new hashmap<string, string>(); static {     messages.put("a", "hello!");     messages.put("b", "again!");     messages.put("c", "etc etc!"); } 

notice how keys uppercase. when letter should convert uppercase too:

letter = message.substring(i,i+1).touppercase(); 

so can message print doing this:

string toprint = messages.get(letter); 

and can print without making 26 switches.


the above solution assumes need print sort of customized text. otherwise others' solutions fine: print letter.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -