Possible Duplicate:
Java String.equals versus ==
我认为这将是构建选择器方法的一种巧妙方式,但输出不会进入前两个 if 语句,而只会输出最后一个
public int myPickerMethod(){
System.out.println("please select from the options ");
System.out.println("please select 1 for option 1 ");
System.out.println("please select 2 please select 2 for option 2");
String input = keyboard.readLine();
System.out.println("input = " + input);
if(input=="1"){
return 1;
}
else if(input=="2"){
return 2;
}
else{
return 42;
}
}
这是我从终端得到的结果:
please select from the options
please select 1 for option 1
please select 2 please select 2 for option 2
1
input = 1
response = 42
如果我输入 2 也是如此。“response”打印语句是来自主类中打印语句的方法的输出。
我以前没有尝试过这种方法,但我认为它应该可行。我真的不明白为什么不是。任何人都可以解决这个问题吗?谢谢
在 Java 中,您需要使用 equals 方法比较字符串:
if ( input.equals("1") ) {
// do something...
}
从 Java 7 开始,您也可以在 switch 语句中使用字符串:
switch ( input ) {
case "1":
// do something...
break;
case "2":
// do something...
break;
}
编辑: 作为对我的回答的补充,这里有一个将 switch 与字符串一起使用的类的示例以及该类的反汇编代码(使用 javap -c)及其工作原理(标签 8 和 11) ).
Foo.java
public class Foo {
public static void main( String[] args ) {
String str = "foo";
switch ( str ) {
case "foo":
System.out.println( "Foo!!!" );
break;
case "bar":
System.out.println( "Bar!!!" );
break;
default:
System.out.println( "Neither Foo nor Bar :(" );
break;
}
}
}
反汇编的 Foo.class 代码:
Compiled from "Foo.java"
public class Foo {
public Foo();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: ldc #2 // String foo
2: astore_1
3: aload_1
4: astore_2
5: iconst_m1
6: istore_3
7: aload_2
8: invokevirtual #3 // Method java/lang/String.hashCode:()I << hashCode here! (I wrote this!)
11: lookupswitch { // 2
97299: 50 // 97299: hashCode of "bar" (I wrote this!)
101574: 36 // 101574: hashCode of "foo" (I wrote this!) (yep, they where swaped. the lesser hashCode first)
default: 61
}
36: aload_2
37: ldc #2 // String foo
39: invokevirtual #4 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
42: ifeq 61
45: iconst_0
46: istore_3
47: goto 61
50: aload_2
51: ldc #5 // String bar
53: invokevirtual #4 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
56: ifeq 61
59: iconst_1
60: istore_3
61: iload_3
62: lookupswitch { // 2
0: 88
1: 99
default: 110
}
88: getstatic #6 // Field java/lang/System.out:Ljava/io/PrintStream;
91: ldc #7 // String Foo!!!
93: invokevirtual #8 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
96: goto 118
99: getstatic #6 // Field java/lang/System.out:Ljava/io/PrintStream;
102: ldc #9 // String Bar!!!
104: invokevirtual #8 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
107: goto 118
110: getstatic #6 // Field java/lang/System.out:Ljava/io/PrintStream;
113: ldc #10 // String Neither Foo nor Bar :(
115: invokevirtual #8 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
118: return
}
一件有趣的事情是,另一个开关是用整数创建的(标签 62),它执行“真正的工作”。