Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

[Java] If-else involving strings

  1. Oct 2, 2013 #1
    I have an if-else piece of code involving strings

    String color = sc.nextLine();
    if (color == "R" || color == "r"){
    System.out.println("red");
    }
    else if (color == "G" || color == "g"){
    System.out.println("green");
    }
    else if (color == "B" || color == "b"){
    System.out.println("blue");
    }
    else{
    System.out.println("Invalid input.");
    }

    Why is it that no matter what input I put in, it always returns invalid input?
     
  2. jcsd
  3. Oct 2, 2013 #2

    DrClaude

    User Avatar

    Staff: Mentor

  4. Oct 2, 2013 #3

    Mark44

    Staff: Mentor

    I'm not sure how string literals are stored in Java, but in C and C++, string literals evaluate to the address of their first byte in memory. IOW, a string literal such as "R" would evaluate to the location of the 'R' character.
     
  5. Oct 2, 2013 #4

    DavidSnider

    User Avatar
    Gold Member

    if (color == "R" || color == "r")

    is better written as:

    if(color.toUpperCase.Equals("R"))
     
  6. Oct 2, 2013 #5

    Mark44

    Staff: Mentor

    On the other hand, if color is of type char, you CAN do this:
    Code (Text):
    if (color == 'R' || color == 'r')
    {
       ...
    }
    else if ((color == 'G' || color == 'g')
    {
       ...
    }
    ...
     
    Note that character literals are delimited by single quotes, not double quotes.
     
  7. Oct 3, 2013 #6
    This will work.

    if (color.equals("R")|| color.equals("r"))
    {
    System.out.println("red");
    }
    else if (color.equals("G") || color.equals("g"))
    {
    System.out.println("green");
    }
    else if (color.equals("B") || color.equals("b"))
    {
    System.out.println("blue");
    }
    else
    {
    System.out.println("Invalid input.");
    }
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: [Java] If-else involving strings
  1. Java If Else Indentation (Replies: 15)

Loading...