Reputation: 1
import javax.swing.JOptionPane;
public class Example {
public static void main(String[] args) {
String colour = JOptionPane.showInputDialog("What's your favourite colour?");
int shade = Integer.parseInt(JOptionPane.showInputDialog("From a scale of 1-10, 10 being the darkest and 1 being the lightest, what shade do you like?"));
String response = "";
if (colour == "Red") {
if (shade < 5)
response = "Light Red";
else
response = "Dark Red";
JOptionPane.showMessageDialog(null, "Your colour is " + response);
}
}
}
Why doesn't the final JOptionPane message show up? For example, the user enters "Red" and then "1", the response isn't showing up as "Light Red".
Upvotes: 0
Views: 166
Reputation: 1943
The most likely explanation is that your code flow is never entering the parent if
block that shows the message dialogue. As the comment on your question stated, this is most likely due to the fact that you are comparing two string using ==
operator instead of the equals(String)
method. Read here for more information about the difference between these two ways of comparing strings.
This is the short summary of the answer linked above:
The equals() method compares the "value" inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not.
The "==" operator compares the value of two object references to see whether they refer to the same String instance.
This is how your code should look like:
String response = "Unknown";
if (colour.equals("Red")) {
response = shade < 5 ? "Light Red" : "Dark Red";
}
JOptionPane.showMessageDialog(null, "Your colour is " + response);
Note that I've taken some liberties in shortening down the assignment of new value to the response
field (as this should make it a more compact and readable) and moved the showMessageDialog
method outside the if
block (as @CarlosHeuberger suggested) so that it provides a message even when the color the user has selected is not red.
Upvotes: 1