开发者

Having trouble using the java "if" statement

I'm trying to teach myself java by writing a simple weekly planner program and the if statment in my code is giving me grief, here is my code:

import java.util.Scann开发者_开发知识库er;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Week
{
 public static void main(String[] args) throws IOException
 {
   Scanner inorout = new Scanner(System.in);
   System.out.println("Do you want to read or write (r/w)");
   String decision = inorout.nextLine();
   System.out.println(decision);
   if(decision == "r")
   {
     System.out.println("It has gone into the if");
     Scanner namer = new Scanner(System.in);
     System.out.println("What is the name of the week you want to read?");
     String r = namer.nextLine();
     Scanner s = new Scanner(new File(r + ".txt"));
     System.out.println("What is Your Name?");
     String name = s.nextLine();
     System.out.println("Welcome " + name);
   }    
 }
}

When I compile the program using Drjava and input "r" it doesn't run the if statment, and i'm at a loss as to whats wrong, help would be much appriciated


Strings in Java are compared usually with equals not with ==.


The String decision will not have reference-equality with the literal "r". You need to use String.equals method.


You should use decision.equals("r").

== check for equality of the references to the objects, not for equality of the objects themselves.


As others have said, you need to use if(decision.equals("r")) instead of if(decision == "r").

Here's a brief explanation on how string references work in Java:

The String class keeps a pool of strings that are currently in use, and if a literal "r" was assigned to decision, or decision was internalized (put into the string pool) using .intern(), it will fetch it from the string pool and the references will be equal. But because decision is set at runtime using user input, it will not be internalized automatically, and the references will not be equal.

In short, in some situations decision == "r" can evaluate to true. But don't rely on it. Use .equals() instead.


if(decision == "r")

== checks for object equality, not string equality you instead need to use the equals() method

if(decision.equals("r"))


Just want to point out that while the decision.equals("r") suggested in many answers will work just fine, it is equally valid to say:

if ("r".equals(decision)) {
   //do something...
}

The benefit of this is that you don't have to worry about "r" ever being null. Also note that you may want to do a case-insensitive comparison in this case (so the user can type 'R' if they want), like:

if ("r".equalsIgnoreCase(decision)) {
   //do something...
}


Try using something like:

if(decision.equals("r"))


you should use the equals method to compare the two strings,the string is a object,this is a reference,the equals() method will compare the content of two strings,but the == will compare the address of two strings

so,you should write like this:

if ("r".equals(decision)) {
//do something code...
}


Equality vs. Identity

You check for identical references (==), or equal objects (.equals()).

Primitive data types (Int, Float, etc.) and references are compaired with ==, complex data types (any normal or self-defined class, String, any object intantiatable by hand via new) have to be compaired by object1.equals(object2).

Strings for example can return false positives for ==, as can be seen in this runnable example here: (copy&paste into File StringComparisonMain.java, compile, run)

/**
 * Difference between identity and equality in java.
 */
public class StringComparisonMain {

    public static void main(String[] args) {

        /*
         * 
         * CREATE TWO DIFFERENT REFERENCES TO TWO DIFFERENT BUT EQUAL STRING
         * OBJECTS
         * 
         * 'two' must be created like this else test will create false
         * positives: one = "asdf"; two = "asdf"; ... will falsely yield 'true'
         * for identity check. This is due to optimizations going in inside the
         * JRE, I believe.
         */
        String one = "bla";
        String two;
        two = "b" + "l";
        two = two + "a";
        String three = "bla";

        /*
         * ACTUAL TESTING CODE
         */
        System.out.println("different reference leading to equal objects:");
        stringCompare(one, two);
        System.out.println("as above, but false positive: (!)");
        stringCompare(one, three);

        // changing to same references to the same String object
        one = two;

        System.out.println("identical references to same single object:");
        stringCompare(one, two);

        // different Strings (and ofc different objects...)
        one = "test";

        System.out.println("different Strings/objects:");
        stringCompare(one, two);

        System.out.println("\nDONE!");

    }

    private static void stringCompare(String stringOne, String stringTwo) {

        // first test for identity (reference to same object)
        if (stringOne == stringTwo) {
            System.out.println("== true");
        } else {
            System.out.println("== false");
        }

        // second test for equality (two referenced objects are equal)
        if (stringOne.equals(stringTwo)) {
            System.out.println("equals true");
        } else {
            System.out.println("equals false");
        }

        // there is not just 'System.out.println' out there...
        System.out.print("\n");
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜