-4
public static void main(String[] args) {
    int i = 0;
    while(i==0){
        System.out.println("Possibilities: R, T, O and X.\nYour choice: ");
        Scanner scan = new Scanner(System.in);
        String bla = scan.nextLine();
        System.out.println(bla);
        if(bla=="R"){
            System.out.println("S or B?\n Your choice: ");
            String derp = scan.nextLine();
            if(derp=="S"){
                String rekeningNummer = spaarRekening.getRekeningNummer();
                }
        }
        if(bla=="T"){
            System.out.println("dit is T");
        }
        if(bla=="O"){

        }
        if(bla=="X"){

        }
        else{
            System.out.println("Impossible. Try again.");
        }
    i+=1;
    }

}

I was trying to run this program, but when it comes across an if statement it ignores it. I don't know why and I am running out of ideas.

Franz Kafka
  • 10,623
  • 20
  • 93
  • 149

5 Answers5

9

To compare String instance, use equals() since it is an Object

See

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
5

Use .equals() .Don't use == because it compares Strings refrences and not Strings characters.

 if (bla.equals("T")) {
     System.out.println("dit is T");
 }
 if (bla.equals("O")) {

 }
sloth
  • 99,095
  • 21
  • 171
  • 219
Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
4

== is not a String comparison operator.

You should use .equals() to compare Strings.

Autar
  • 1,589
  • 2
  • 25
  • 36
1

Let's assume we have two strings. String str1= "blah"; String str2= new String("blah");

There are two levels of equality chacking in Java.

  1. You may want to test whether the two referance variable str1 and str2 points to the same String object. we usually do this check by str1==str2.

  2. You may want to test whether Strings referenced by str1 and str2 are equal in their meaning. we usually do this by invoking equals method i.e. str1.equals(str2) or str2.equals(str1).

To be more clear, your statement "bla=="R"" checks whether referances returned by ""R"" and and bla point to the same object or not, which is not actually the thing you want. You want to check whether String referanced by bla is equal to "R" by meaning or not. So If you want to compare objects by meaning in java, you will have to call equals() method on that object.

Ahmad
  • 2,110
  • 5
  • 26
  • 36
0

Don't use == use .equals() since it is an String Object

chaitu
  • 599
  • 1
  • 6
  • 13