Reputation: 17
Here is my current code:
import java.util.Scanner;
public class Random {
public static void main(String ars[]){
Scanner input = new Scanner(System.in);
System.out.println("Welcome");
hey = input.nextLine();
if(hey == "M"){
System.out.println("Yup");
}else{
System.out.println("Nope");
}
}
}
I am very new to Java, and to me, this looks like it should work, but Java is telling me "hey cannot be resolved to a variable.
I looked through some different Java reference guides on the internet, and thought for a while, and I still can't figure out why it won't work.
Upvotes: 2
Views: 86
Reputation: 285401
where do you declare the hey variable?
answer: you don't.
So declare it:
String hey = input.nextLine();
Also,...
Don't compare Strings using ==
. Use the equals(...)
or the equalsIgnoreCase(...)
method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of
if (fu == "bar") {
// do something
}
do,
if ("bar".equals(fu)) {
// do something
}
or,
if ("bar".equalsIgnoreCase(fu)) {
// do something
}
Upvotes: 6