2013-11-27 43 views
-5

這應該是很簡單,但它讓我難住了!查詢字符串的聲明如果比較

可以說我有一個頁面:mysite.com/mypage.jsp

當它被提交到自身的網址是:mysite.com/mypage.jsp?myvalue=blah

我已經得到了以下代碼,這些代碼從來不等於真,我做錯了什麼?

String myvalue = request.getParameter("myvalue"); 

if (myvalue == "blah") { 
out.print("<h3>You submitted the page, my value = " + myvalue + "</h3>"); 

} else { 
    out.print("<h3>Page not submitted yet, my value = " + myvalue + "</h3>"); 
} 
+0

對不起,現在有道理 – Scott

回答

2

取代if (myvalue == "blah") { 到如果(myvalue.equals("blah")) {

String myvalue = request.getParameter("myvalue"); 

if (myvalue.equals("blah")) { 
out.print("<h3>You submitted the page, my value = " + myvalue + "</h3>"); 

} else { 
    out.print("<h3>Page not submitted yet, my value = " + myvalue + "</h3>"); 
} 
+0

謝謝你現在工作。 – Scott

0

爲了比較在Java使用.equals字符串對象()方法,而不是 「==」 操作者

更換以下代碼

if (myvalue == "blah") 

if ("blah".equals(myvalue)) 

如果你想忽略大小寫使用equalsIgnoreCase()

if ("blah".equalsIgnoreCase(myvalue)) 
0

我有下面的代碼,從來沒有等同於真實的,什麼是我 做錯了什麼?

您應該使用equals方法而不是==。嘗試使用null safe equals

"blah".equals(myvalue) 
0

使用equals()equalsIgnoreCase()

myvalue.equalsIgnoreCase("blah") 
0

與大家上面,你需要使用字符串比較.equals,否則比較的對象,而不是字符內容。

您還應該知道,使用.equals時,應始終將常量放在左側,以避免出現空指針。

可怕:

// because strings are objects, this just compares the 2 objects with each other, 
//and they won't be the same, even if the content is, they are separate instances. 
if (myvalue == "blah") 

壞:

//if you didn't have a myvalue, this would go bang 
//(unless you add a null check in as well) 
if (myvalue.equals("blah")) 

好:

if ("blah".equals(myvalue)) 
1

您可以使用contentEquals字符串。

link解釋你diffrence的B/W equalcontentEquals

String myvalue = request.getParameter("myvalue"); 

    if (myvalue.contentEquals("blah")) 
    { 
     out.print("<h3>You submitted the page, my value = " + myvalue + "</h3>"); 
    } 
    else 
    { 
     out.print("<h3>Page not submitted yet, my value = " + myvalue + "</h3>"); 
    }