快速替代许多if语句 [英] Quick alternative to lots of if statements
本文介绍了快速替代许多if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Java的初学者,我正在制作一个简单的程序,在其中键入内容,如果键入的内容与数据库"上的内容之一匹配,则它将打印一些文本.有没有比这更简单的方法来检查这一点:
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;
等
if([USER INPUT].equals("1")) {
System.out.println("TEST");
}
400次.
推荐答案
使用switch语句或HashMap.
Use a switch statement or a HashMap.
switch语句:可读,但与if-else链的编译方式类似(如果不相同).
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);
这篇关于快速替代许多if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文