java - Quick alternative to lots of if statements -


i'm beginner @ java, , i'm making simple program type in something, , if type in matches 1 of things on "database" it'll print text. there simpler way check rather doing this:

int 1; int 2; int 3; 

etc.

if([user input].equals("1")) {     system.out.println("test"); } 

400 times.

use switch statement or hashmap.

switch statement: readable, compiles (if not identically) if-else chain.

switch([user_input]) {     case 1:         system.out.println("test");         break;     case 2:         system.out.println("hello");         break;     // , on. } 

hash map: more readable , simpler. preferred.

// initialization. map<integer,string> map = new hashmap<integer,string>(); map.put(1,"test"); map.put(2,"hello");  // printing. string s = map.get(user_input); if (s == null)     system.out.println("key doesn't exist."); system.out.println(s); 

Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -