Skip to main content
GameDev.net gamedev.net
🔒 Locked

Java Problem

Started by drackill Nov 2, 2005 at 3:42 PM 3 replies 950+ views
Original Post
drackill
drackill
Hello i'm fairly new to programming in Java and I have come across a problem import javax.swing.JOptionPane; class Exercise6 { public static void main(String[] args) { String response, a, b, c, d, e, f; int i; int[] grades; i = 1; grades = new int[5]; response = JOptionPane.showInputDialog("Enter Grade Mark" + i); if (response =="a" || response =="A"){ grades[0] = grades[0] + 1; System.out.println("ITS WORKED"); } else { response = "Must enter either A, B, C, D, E or F"; JOptionPane.showMessageDialog(null, response); } System.exit(0); } } the problem lies in the if statement for some reason when I put a or A in the little input box that appears it seems to read it as something else cause it makes both conditions false and skips to the else statement. I think its something to do with JOptionPane but I have no idea. I've tried just initilizing a varible with the value of A or a and skipping the JOptionPane thing and that worked. Any advice would be appreciated. Thank you
Sharlin
Sharlin
Strings in Java are objects, and thus have reference semantics. That is, comparing two strings with the == operator only checks whether the two references actually point to the same string in memory, not whether two strings have an equal content. For the latter, you'll have to use the equals() method:
if(result.equals("a") || result.equals("A"))
yarniso
yarniso
If I am correct (my java-days are some years back) you can compare strings by using the equals() method. Using '==' will give you wether or not the two objects are physically the same. And in this case that will always result in false.

edit: Sharlin beat me to it. But good to see that I'm not that rusty after all.
drackill
drackill
Thank you very much, it works now.

Thank you for your time and also an explanation. Makes more sense now.
Mattman
Mattman
I believe there is also an "equalsIgnoreCase" that you could use so you don't need to test both "a" and "A"... I may be thinking of &#106avascript though, which may be different. Alternatively, you could just do this:<br><br>...<br>if(result.toUpperCase().equals("A"))<br>...

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.