Re: Need help with my code
sc.nextLine() returns a string, not a boolean. What happens if someone types in "blah", how can that be a boolean value(true/false). If you intend to get a string variable, store it in a String variable. In your code, input is a boolean, "Hello my friend" != null returns true as long as the string is not null. If this makes sense--good. If not ask me to clarify, and I will.
Re: Need help with my code
Quote:
boolean input = sc.nextLine() != null;
Instead of trying to do two things in one statement, break this statement into two simple statements.
1) get the input
2) test it
Re: Need help with my code
Thanks for the help guys :) i changed the variable to a string and then it underlines "input = "Hello my friend" and says i cannot covert it
from a string to a boolean. Can i just simply not have an if statement for a String variable? Is there anyway to go around that? For example, i want the console to respond to the user if he says a certain thing. Sorry if im not making sense.
Re: Need help with my code
Check out the .equals(Object o) method. String (Java Platform SE 6)
Re: Need help with my code
Can you post the code with the problem?
The following statement has a boolean on the left and a String on the right
Code:
boolean input = "Hello my friend";
That doesn't work. You need
either a String variable on the left
or a boolean expression on the right.
Re: Need help with my code
Code:
import java.util.Scanner;
public class MainClass {
public static void main(String[] args){
Scanner sc = new Scanner (System.in);
String input = sc.nextLine();
System.out.println(input);
if ([U]input = "Hello my friend"[/U]){
System.out.println("Ahh, hello there!");
}
}
}
Re: Need help with my code
When posting code, please use code tags: [code] YOUR CODE HERE [/code]
Also, '=' is an assignment operator, comparisons is done with '==' and strings need to be compared with .equals(Object o)
Re: Need help with my code
Is there something different besides a string or boolean that i can use? I looked at the .equals (Object o) method. I dont really understand that. It said it was a "superclass" or something...
Re: Need help with my code
oh sorry about that :/ i was wondering how to do that haha
Re: Need help with my code
Ohhhh hold on i think i know how to fix it..
Re: Need help with my code
Alright i fixed it all i had to do was change it from '=' to '=='. Thanks guys!
Re: Need help with my code
That is still actually incorrect. For primitives it is fine to use '==' but for strings this compares references--which is not what you want. Instead use equals.
Code:
string1.equals(otherString)
Will return true if the two strings are equal.
Re: Need help with my code
Hold on ill try that right now
Re: Need help with my code
Ok i got it.. I'll look into that area more. Thanks for the help!