0

重複の可能性:
Java で文字列を比較するにはどうすればよいですか?

2 つの文字列 "abc" と "de" を比較するコードを書きました。文字列 abc が解析され、「doc」から ext に返されて比較されます。if 条件が true のように見えますが、まだ else 部分が実行されています。私が得られないところで助けてください....どうもありがとう。

public class xyz{

    String abc="doc2.doc";
    String de="doc";

    public static void main(String arg[]){

    xyz c=new xyz();

    String ext = null;
    String s =c.abc;
        String d =c.de;
    int i = s.lastIndexOf('.');

    if (i > 0 && i < s.length() - 1){
    ext = s.substring(i+1).toLowerCase();
    }
    System.out.println(ext);
    if(ext==d){

    System.out.println("true");
    }
    else{
    System.out.println("false");
    }


    }


    }
4

7 に答える 7

3

==文字列を演算子と比較することはできません。

使用する必要がありますString.equals()

あなたの場合、それは

if (ext.equals(d)) {
    System.out.println("true");
} else {
    System.out.println("false");
}
于 2012-10-03T10:52:35.167 に答える
1

==参照の等価性をテストします。

.equals()値が等しいかどうかをテストします。

したがって、実際に 2 つの文字列が同じ値かどうかをテストしたい場合は、.equals() を使用する必要があります。

// These two have the same value
new String("test").equals("test") ==> true 

// ... but they are not the same object
new String("test") == "test" ==> false 

// ... neither are these
new String("test") == new String("test") ==> false 

この場合

if(ext.equals(d)) {
    System.out.println("true");
}
else {
    System.out.println("false");
}
于 2012-10-03T10:53:43.823 に答える
0

あなたは.equals()でそれを書くことができます..

private String a = "lol";

public boolean isEqual(String test){
  return this.a.equals(test);
}
于 2012-10-03T10:56:25.420 に答える
0

演算子を使用しequalsて文字列を比較します。

ext.equals(d)
于 2012-10-03T10:54:41.633 に答える
0

文字列は異なるオブジェクトであるため、== と比較することはできません。内容は同じかもしれませんが、それは == が見ているものではありません。文字列の 1 つで equals メソッドを使用して、それを他の文字列と比較します。

コードでは、次を使用します。

if(d.equals(ext)){

2 つの文字列を比較する必要があり、そのうちの 1 つだけが変数である場合は、次のアプローチをお勧めします。

"foo".equals(variableString)

このようにして、Null オブジェクトで equals を呼び出さないようにすることができます。

もう 1 つの可能性は、他の Java クラスにも見られる equals メソッドの代わりに、compareTo メソッドを使用することです。文字列が一致すると、compareTo メソッドは 0 を返します。

Java の文字列の詳細については、こちらを参照してください。

于 2012-10-03T10:59:27.257 に答える
0

あなたは書くべきです

if(ext.equals(d))

instead of 

if(ext==d)
于 2012-10-03T11:02:22.500 に答える
0
String str1, str2, str; // References to instances of String or null

str1 = "hello"; // The reference str1 points to an instance of "hello" string
str2 = "hello"; // The reference str2 points to another instance of "hello" string
str3 = str2;    // The reference str3 points to the same instance which str2 does.

assert str1.equals( str2 ); // Both string instances are identical.
assert str1 != str2;        // Both references point to independent instances of string.
assert str2 == str3;        // Both references point to the same instance of string.
于 2012-10-03T11:17:35.313 に答える