簡體   English   中英

Java if() 不工作

[英]Java if() not working

當我運行一些代碼時(稍后顯示),我告訴它檢查字符串是否 == "1",如果是,output "It's 1,",否則。 output 字符串。

代碼:

double shirt3 = Math.random() * 9;
String shirt2 = Double.toString(shirt3);
char shirt1 = shirt2.charAt(0);
String shirt = Character.toString(shirt1);

if(shirt == "1") {
    System.out.println("It's 1!");
} else {
    System.out.println(shirt);
}

Output:

7
4個
8個
1個
7
1個
7
7
6個
0

你需要使用

if (shirt.equals("1"))
    ...

這將比較 String 對象的實際內容,而不是它們的標識。

您犯了 Java 初學者的錯誤,即使用==來測試 String 是否相等。 請改用equals方法。

更長的解釋是 Java 中的==運算符測試兩個 object 引用是否相同; 即它測試左右操作數是否相同 object。但是您擁有的是兩個包含相同字符序列的不同字符串。 它們是“相等”的字符串,但不是相同的 object。

作為一般經驗法則,您應該始終使用equals來比較字符串。

(在某些情況下==會起作用,但您確實需要了解自己在做什么才能確定。在絕大多數用例中,這根本不值得付出努力/冒險。)

要檢查 Java 中的兩個字符串是否相同,請使用.equals()

"1" == new String("1") //returns false
"1".equals(new String("1")) //returns true

編輯:添加了 new String("1") 以確保我們正在談論一個新字符串。

除此之外,您還需要使用 equals 方法來比較 java 中的字符串

// it't allways a good idea to use constant.equals(...)
// to avoid possible NullPointerExceptions
if ("1".equals(shirt))
    ...

在您的情況下,您不必將字符轉換為字符串,您也可以比較單個字符。 在不創建額外的 String object 的情況下執行相同的操作,並且您不必處理 equals 方法。

if (shirt1 == '1')
        ...

要比較字符串,請使用等於。

if(shirt.equals("1"))
     System.out.println("It's 1!");
    }else{
        System.out.println(shirt);
    }

一個更通用的規則是不要讓代碼變得比它需要的更復雜。

int shirt = (int)(Math.random() * 10); // shirt numbers from 0 to 9.
if(shirt == 1) 
    System.out.println("It's 1!");
else 
    System.out.println(shirt);

這說明==可用於比較原語。 它也可以用來比較引用,但不能用來比較對象的內容。

Double d = 0.1;
Double e = 0.1;
System.out.println("(Double) 0.1 == (Double) 0.1 is " + (d == e));

double x = 0.1;
double y = 0.1;
System.out.println("0.1 == 0.1 is " + (x == y));

印刷

(Double) 0.1 == (Double) 0.1 is false
0.1 == 0.1 is true

這表明當比較Double時,像字符串一樣,對象==不比較內容。

當使用緩存時,所有這一切都有一個混淆,就像字符串文字的情況一樣。 這意味着出於性能原因,在不同地方引用的值實際上使用相同的 object。

Integer d = 10;
Integer e = 10;
System.out.println("(Integer) 10 == (Integer) 10 is " + (d == e));

int x = 10;
int y = 10;
System.out.println("10 == 10 is " + (x == y));

印刷

(Integer) 10 == (Integer) 10 is true
10 == 10 is true

第一個示例有效,因為 Java 5.0+ 使用小整數緩存。 (小的integer的大小因命令行參數而異:})

Integer d = -129;
Integer e = -129;
System.out.println("(Integer) -129 == (Integer) -129 is " + (d == e));

int x = -129;
int y = -129;
System.out.println("-129 == -129 is " + (x == y));

印刷

(Integer) -129 == (Integer) -129 is false
-129 == -129 is true

至於字符串,使用了字符串文字緩存。 此外,編譯器將簡化常量表達式,因此以不同方式編寫的字符串可以是相同的。

final int one = 1;
int oneB = 1;
String a = "1";
String b = "" + 1;
String c = "" + one;
String d = "" + oneB;

System.out.println(a == b);
System.out.println(a == c);
System.out.println(a == d);

印刷

true
true
false

每個字符串的內容是相同的,但oneB不是常量,因此表達式在運行時計算並產生不同的字符串。

恕我直言: equals試圖向開發人員隱藏詳細信息,將==調用等於是一個更好的選擇,而如果您真的想比較實際引用,則可以使用運算符===

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM