Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick alternative to lots of if statements

I'm beginner at java, and I'm making a simple program where I type in something, and if what I type in matches one of the things on the "database" then it'll print some text. Is there a simpler way to check this rather than doing this:

int 1;
int 2;
int 3;

etc.

if([USER INPUT].equals("1")) {
    System.out.println("TEST");
}

400 times.

like image 580
user3532547 Avatar asked Apr 14 '14 15:04

user3532547


People also ask

What is better than multiple if statements?

Switch statement works better than multiple if statements when you are giving input directly without any condition checking in the statements. Switch statement works well when you want to increase the readability of the code and many alternative available.

Which is equivalent to multiple if-else if statements?

In this case, when one IF statement is used inside another IF statement, this is called the nested IF statement. This allows to use more than one condition simultaneously.


1 Answers

Use a switch statement or a HashMap.

Switch statement: Readable, but compiles similarly (if not identically) to an if-else chain.

switch([USER_INPUT]) {
    case 1:
        System.out.println("TEST");
        break;
    case 2:
        System.out.println("HELLO");
        break;
    // And so on.
}

Hash Map: Much more readable and simpler. This is 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);
like image 55
Anubian Noob Avatar answered Oct 17 '22 16:10

Anubian Noob