Java if() does not work

When I run some code (shown later), I tell it to check the string = = "1". If so, output "it is 1!", Otherwise, the string is output

Code:

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

Solution

You need to use

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

This compares the actual contents of string objects rather than their identities

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>