mercredi 14 janvier 2015

When using the Scanner function in Java, how do I set the input equal to a String in my "if" statement? [duplicate]


This question already has an answer here:




I'm trying to make a program that asks two questions and based off the answers to the questions, I have a generated response. It's like 20 questions but with only two questions (from ProgrammingByDoing.com). However, I can't seem to get my if statements to work as the program always bypasses them. I think I am incorrectly setting the input String equal to another String.

Here's my code:


import java.util.Scanner;


public class TwentyQuestions


{



public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);

System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I'll try to guess it.");
System.out.println(" ");

String first_answer;
String second_answer;

System.out.println("Question 1) Is it animal, vegetable, or mineral?");
first_answer = keyboard.next();

if ( first_answer == "animal")
{
System.out.println("Question 2) Is it bigger than a breadbox?");
second_answer = keyboard.next();
if ( second_answer == "no")
{
System.out.println("My guess is that you are thinking of a squirrel");
}
else
{
System.out.println("My guess is that you are thinking of a moose");
}

}

else if ( first_answer == "vegetable")
{
System.out.println("Question 2) Is it bigger than a breadbox?");
second_answer = keyboard.next();
if ( second_answer == "no")
{
System.out.println("My guess is that you are thinking of a carrot");
}
else
{
System.out.println("My guess is that you are thinking of a watermelon");
}
}
else if ( first_answer == "mineral")
{
System.out.println("Question 2) Is it bigger than a breadbox?");
second_answer = keyboard.next();
if ( second_answer == "no")
{
System.out.println("My guess is that you are thinking of a paper clip");
}
else
{
System.out.println("My guess is that you are thinking of a Camaro");
}
}
System.out.println("I would ask if I'm right, but I don't actually care.");

}


}


Aucun commentaire:

Enregistrer un commentaire