我是 Java 的初学者,我正在编写一个简单的程序,我在其中输入一些内容,如果我输入的内容与“数据库”中的其中一个内容相匹配,它就会打印一些文本。有没有更简单的方法来检查这个而不是这样做:
int 1;
int 2;
int 3;
等等
if([USER INPUT].equals("1")) {
System.out.println("TEST");
}
400 次。
最佳答案
使用 switch 语句或 HashMap。
Switch 语句:可读,但与 if-else 链的编译方式类似(如果不完全相同)。
switch([USER_INPUT]) {
case 1:
System.out.println("TEST");
break;
case 2:
System.out.println("HELLO");
break;
// And so on.
}
Hash Map : 更具可读性和更简单。这是首选。
// 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);
关于java - 快速替代大量 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23063750/