简体   繁体   English

如何在if-else语句中比较字符串?

[英]How to compare Strings in if-else statements?

I wonder if anyone could give me a pointer with some pre-population in JSP: 我想知道是否有人可以在JSP中给出一些预先填充的指针:

So I am attempting to pre-populate a checkbox depending on the value in the customers database record. 所以我试图根据客户数据库记录中的值预先填充一个复选框。 The checkbox would be checked if there is a 1 in the field, the other option would be a 0 - where the checkbox should be empty. 如果字段中有1,则检查复选框,另一个选项为0 - 其中复选框应为空。

I am currently using this code within the input: 我目前在输入中使用此代码:

<%if (UPDATEDPREFERENCES != null)
{ 
    if (ISNEWSLETTER != "0") {
        out.println("checked");
    } 
}
%>

so it would be: 所以它会是:

<input type='checkbox' class="newsletter" name='temp_ISNEWSLETTER_FIELD' id="temp_ISNEWSLETTER_FIELD" <%if (UPDATEDPREFERENCES != null)
{ 
    if (ISNEWSLETTER != "0") {
        out.println("checked");
    } 
}
%>/>

As it stands, it pre-populates fine. 就目前而言,它预先填好了。 However, it also populates if the field is 0. If I change it to read: 但是,如果字段为0,它也会填充。如果我将其更改为:

if (ISNEWSLETTER == "1")

then the checkbox is empty whether it's a 1 or 0. 然后复选框为空,无论它是1还是0。

Am I missing something obvious? 我错过了一些明显的东西吗 I am not a developer, I am in NYC and my support is in Belgium - they've all left for the day. 我不是开发人员,我在纽约,我的支持在比利时 - 他们都离开了这一天。

Strings are objects , not primitives . 字符串对象 ,而不是基元 Use equals() , not == / != . 使用equals() ,而不是== / != The == / != won't check if they contain the same value, but if they point to the same object reference. == / !=不会检查它们是否包含相同的值,但是它们是否指向相同的对象引用。 The equals() will check if they contain the same value. equals()将检查它们是否包含相同的值。

So, instead of if (ISNEWSLETTER != "0") you should use 所以,而不是if (ISNEWSLETTER != "0")你应该使用

if (!ISNEWSLETTER.equals("0"))

and instead of if (ISNEWSLETTER == "1") you should use 而不是if (ISNEWSLETTER == "1")你应该使用

if (ISNEWSLETTER.equals("1"))

This problem is not related to JSP. 此问题与JSP无关。 You would have exactly the same problem when doing so in a normal Java class (where this kind of code actually belongs). 在普通的Java类(这种代码实际上属于这种类)中执行此操作时,您会遇到完全相同的问题。

As an alternative, since they represent numbers, you could also just convert ISNEWSLETTER to an int . 作为替代方案,因为它们代表数字,您也可以将ISNEWSLETTER转换为int It's a primitive, so you should be able to use == / != the usual way. 这是一个原始的,所以你应该能够使用== / !=通常的方式。 You can if necessary convert a String to an int using Integer#parseInt() . 如有必要,您可以使用Integer#parseInt()String转换为int Or, even more, if it actually represents a boolean state (it can only be true or false ), then you should rather use boolean instead. 或者,甚至更多,如果它实际上表示一个布尔状态(它只能是truefalse ),那么你应该使用boolean代替。 You can just use it straight in the if condition without any need for comparisons. 您可以直接在if条件下使用它而无需进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM