Re: String or Boolean help
one = is 'assignment', it means copy the value on the right to the variable on the left. The type of an 'x = y' expression is the type of x, so String x = "a letter y" is an expression with a String type.
two =, like == is 'test for equality', compare the left side to the right side and return boolean true if they're the same, boolean false otherwise. It doesn't matter what type x and y are in x == y, the type of the expression is boolean.
If statements are if ([boolean_expression]) - no other type of expression is allowed.
Re: String or Boolean help
Quote:
Originally Posted by
Sean4u
one = is 'assignment', it means copy the value on the right to the variable on the left. The type of an 'x = y' expression is the type of x, so String x = "a letter y" is an expression with a String type.
two =, like == is 'test for equality', compare the left side to the right side and return boolean true if they're the same, boolean false otherwise. It doesn't matter what type x and y are in x == y, the type of the expression is boolean.
If statements are if ([boolean_expression]) - no other type of expression is allowed.
i am ashamed, i have watched so many tutorials, and actually used that before (the ==) my brain was out of it, thank you :o
ok, now i don't know if this is the way i worded the code or not, but no-matter what i type, it still goes with the second argument (I do not reconize that statement)
Here is my updated code:
Code Java:
import java.util.Scanner;
public class ScannerMain {
public static void main (String args[]){
Scanner wordscanner = new Scanner(System.in);
boolean con = true;
while (con = true) {
String answer;
System.out.print("Reply:");
answer = wordscanner.next();
if (answer == "hi"){
System.out.println("Hello");
}else{
System.out.println("I do not reconize your statement");
}
}
}
}
Thanks for your help!!
Re: String or Boolean help
== compares the left hand side with the right hand side. answer's 'type' is a String reference - it's a reference that you assigned to a (reference to a) String object returned from your Scanner's next() method. "hi" is another, completely separate String object which has its own reference. The two references are not the same. '==' is doing the very shallowest of comparisons between the two reference types. It is asking "is the left hand side referring to the same object that the right hand side is referring to?". If you want to do something deeper (like compare the content of the two objects to see if they hold the same sequence of characters), you'll need to use the equals() method. Read the API documentation for Object.equals and String.equals
Re: String or Boolean help
Keep in mind that the == operator will only work for primitive data types (char, int, double, float...ect.). When comparing Objects, in this case Strings, you should use the equals() method provided by the Object class.