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.

有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top