Results 1 to 6 of 6
- 02-09-2012, 06:29 PM #1
Member
- Join Date
- Feb 2012
- Posts
- 2
- Rep Power
- 0
If Statements with string values.
Hello:
I am new to Java and am struggling with string values as variables... I have the following small class that just isn't working. My problem is that even when I enter "YES" or "NO", my return response is "Please Enter Yes or No". I suspect I am not using the readLine command correctly and the hard return is causing the problem but not sure.
Thanks for the help.
public void run(){
while(true){
println(respond(readLine("Would You Like Instructions?")));
}
}
private String respond(String str){
if(str=="YES"){return "Instructions";}
else if (str=="NO"){return "Ok";}
else {return "Please Enter Yes or No";}
}
- 02-09-2012, 06:31 PM #2
Senior Member
- Join Date
- Feb 2011
- Location
- Georgia, USA
- Posts
- 122
- Rep Power
- 0
Re: If Statements with string values.
"==" compares object references.
equals() comapres the actual value of the string
tryJava Code:if(str.equals("YES"))
- 02-09-2012, 06:31 PM #3
Re: If Statements with string values.
You should use the equals() method to compare Strings, not the == operator.
- 02-09-2012, 06:34 PM #4
Member
- Join Date
- Feb 2012
- Posts
- 2
- Rep Power
- 0
Re: If Statements with string values.
Thanks for the help, and the forum
Best regards,
Crafty
- 02-10-2012, 12:53 AM #5
Re: If Statements with string values.
As a general rule, I only use == for comparing primitive data types (float, int, double, char, boolean, etc.) in Java. The .equals() method is for comparing Objects.
If you aren't programming in Java, well that's just too bad.
I'd rather be using Ubuntu.
- 02-10-2012, 01:31 AM #6
Re: If Statements with string values.
Why do they call it rush hour when nothing moves? - Robin Williams
Similar Threads
-
Returner values from if statements
By gabrielpr12 in forum New To JavaReplies: 6Last Post: 01-27-2012, 01:03 PM -
String If Statements
By anthropamorphic in forum New To JavaReplies: 7Last Post: 06-22-2011, 03:23 PM -
Problems with writing String values to a text file
By Tedward in forum New To JavaReplies: 8Last Post: 06-02-2011, 04:28 AM -
Sorting string Array Values
By Zerpol in forum New To JavaReplies: 1Last Post: 01-14-2011, 07:08 AM -
Passing values to main(String args[]) ?
By al_Marshy_1981 in forum New To JavaReplies: 6Last Post: 02-21-2010, 10:16 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks