3

重複の可能性:
Java String.equals と ==

これはピッカー メソッドを構成するためのきちんとした方法だと思いましたが、出力は最初の 2 つの 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を入れても同じです。「応答」printステートメントは、メインクラスのprintステートメントからのメソッドからの出力です。

以前にこの方法を試したことはありませんが、うまくいくはずだと思いました。なぜそうでないのか、私にはよくわかりません。これをクリアできる人いますか?ありがとう

4

6 に答える 6

9

Java では、equals メソッドを使用して文字列を比較する必要があります。

if ( input.equals("1") ) {
    // do something...
}

Java 7 以降、switch ステートメントでも文字列を使用できます。

switch ( input ) {

    case "1":
        // do something...
        break;

    case "2":
        // do something...
        break;

}

編集:私の答えを補完するために、文字列とクラスの逆アセンブルコード(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        
}

1 つの興味深い点は、別のスイッチ (ラベル 62) が整数で作成され、それが「実際の作業」を行うことです。

于 2012-07-23T17:59:11.893 に答える
5

1. Java で.equals比較するために使用し、JavaのオブジェクトですObjectsString

例えば: if(input.equals("1"))

2.これはオプションですが、 Scanner クラスを使用する場合にも有効です。

例えば:

Scanner scan = new Scanner(System.in);
String input = scan.nextLine();

3.ラダーの代わりにswitchステートメントを使用することもお勧めします.switchを使用する場合. if-elseString jdk 1.7 or above 1.7

于 2012-07-23T17:57:58.713 に答える
5

オブジェクト (非プリミティブ型) の等価性をテストするには、 を使用しますObject.equals()

if(input.equals("1")) {

    return 1;
}

オペレーターは、オブジェクトへの==参照が等しいかどうかをチェックします。参照の等価性のテストはString.equals() method、他のチェックの中でもとりわけ、 内で実行されます。String.equals()以下は、メソッドの Java ソースです。

public boolean equals(Object anObject) {
     if (this == anObject) {      // Reference equality
         return true;
     }
     if (anObject instanceof String) {
         String anotherString = (String)anObject;
         int n = count;
         if (n == anotherString.count) {  // Are the strings the same size?
             char v1[] = value;
             char v2[] = anotherString.value;
             int i = offset;
             int j = anotherString.offset;
             while (n-- != 0) {
                 if (v1[i++] != v2[j++])        // Compare each character
                     return false;
             }
             return true;
         }
     }
     return false;
}
于 2012-07-23T17:58:36.083 に答える
3

文字列 (または任意のオブジェクト) の値を で比較しないでください==equalsのようなメソッドを使用しif(input.equals("1"))ます。

==たとえば、参照に同じオブジェクトが含まれているかどうかを確認するために使用されます

Integer i1=new Integer(1);
Integer i2=new Integer(1);
Integer i3=i1;
//checking references
System.out.println(i1==i2);//false
System.out.println(i1==i3);//true

//checking values
System.out.println(i1.equals(i2));//true
System.out.println(i1.equals(i3));//true
于 2012-07-23T17:57:43.247 に答える
3

オブジェクト比較はすべきで.equalsはなく==Stringオブジェクトです。

input=="1" は input.equals("1") にする必要があります

EDIT==以下は、リテラルであり、Java が同じメモリ位置を割り当てるため、 使用しても常に機能します。

 String s ="Hi";
 String s1= "Hi";

 if(s==s1)
 {
     System.out.println("Yes they are same");
 }

ただし、2 つの別々の文字列を読み取る場合、 and(new String())をオーバーライドしないequalshashcode、等価条件が満たされない場合があります。詳細については、上記のリンクをお読みください。

于 2012-07-23T17:57:52.620 に答える
1

使用equals方法……

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.equals("1")){

            return 1;
    }
    else if(input.equals("2")){
        return 2;
    }
    else{
        return 42;
    }

}

于 2012-07-23T17:59:44.383 に答える