Reputation: 41
import java.util.Scanner;
public class Questionaire {
public static void main(String[] args) {
String name;
String ansOne;
Scanner input = new Scanner(System.in);
System.out.print("Hello, welcome to the super awesome quiz. Let's get things going. What is your name?");
name = input.nextLine();
System.out.print("Okay, hi " + name + " I'm just going to call you Bob.");
System.out.print(" Question 1: What is the name of your dog?");
ansOne = input.nextLine();
if (ansOne == "Avagantamos") {
System.out.print("Correct!");
} else {
System.out.print("Wrong! The correct answer was Avagantamos!");
}
}
}
So basically, when it asks you to type in the name of your dog, it's always incorrect, even when you type Avagantamos. I'm still really noob and this has been really frustrating so thank you so much to whoever responds.
Upvotes: 4
Views: 310
Reputation: 133634
Use ansOne.equals("Avagantamos")
==
compares the references of the objects.
Upvotes: 2
Reputation: 30647
When comparing strings, use .equals()
, not ==
. This is because ==
compares objects according to reference identity, and there may be multiple String
instances that contain the same data. The .equals()
method will compare the contents of the String
s, which is what you want. So you should write
if (ansOne.equals("Avagantamos")) {
In this case, it seems that input.nextLine()
is constructing a new String
object, which is why ==
doesn't work.
Incidentally, you probably wanted to use System.out.println
rather than .print
; otherwise the prompts and output will all be run together on one line.
Upvotes: 2
Reputation: 285405
Don't use ==
to compare Strings. Use the equals(...)
or equalsIgnoreCase(...)
method.
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 (fu.equals("bar")) {
// do something
}
or,
if (fu.equalsIgnoreCase("bar")) {
// do something
}
Upvotes: 9