Question

I have the following code:

public void convert()
{

    String val = (String) spinner1.getItemAtPosition(spinner1.getSelectedItemPosition());
    System.out.println(spinner1.getItemAtPosition(spinner1.getSelectedItemPosition()));
    System.out.println(val);
    if(val == "mm" || val == "cm" || val == "m" || val == "km")
    {
        System.out.println("got into if statements");
        initiateLengthConvert();
    }
    System.out.println("never got it");



}

Now when the first to print statements print out, if I selected "mm", then it prints out:

mm
mm
never got it

Why won't it pass into the if statement? "val" and the possibilities match up, so it doesn't make any sense to me.

Était-ce utile?

La solution

Use .equals to compare strings instead of ==.

if(val.equals("mm") || val.equals("cm") || val.equals("m") || val.equals("km"))

Read

What is the difference between == vs equals() in Java?

Also instead of System.out.println("..."); use Log

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top