[Java] If-else involving strings

  • #1
86
0
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?
 

Answers and Replies

  • #3
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.
 
  • #4
if (color == "R" || color == "r")

is better written as:

if(color.toUpperCase.Equals("R"))
 
  • #5
On the other hand, if color is of type char, you CAN do this:
Code:
if (color == 'R' || color == 'r')
{
   ...
}
else if ((color == 'G' || color == 'g')
{
   ...
}
...
Note that character literals are delimited by single quotes, not double quotes.
 
  • #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.");
}
 

Suggested for: [Java] If-else involving strings

Replies
8
Views
598
Replies
10
Views
1K
Replies
1
Views
303
Replies
5
Views
903
Replies
17
Views
841
Replies
2
Views
751
Replies
2
Views
950
Back
Top