r/programmingbydoing • u/FancyMonocle • Feb 06 '13
Exercise 33: Twenty Questions - Nested if statements not working?
I used the nested if statements like the assignment told me to, but they aren't being used by the program. The program just skips to the end after asking the final question and nothing is displayed.
import java.util.Scanner;
public class twoquestions
{
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.\n");
System.out.println("1. Is it an animal, vegetable, or mineral?");
String q1 = keyboard.next();
System.out.println("2. Is it bigger than a breadbox?");
String q2 = keyboard.next();
if(q1 == "animal")
{
//System.out.println("test1");
if (q2 == "no")
{
System.out.println("\bMy guess is that you are thinking of a squirrel.");
System.out.println("I would ask you if I'm right, but I don't actually care.");
}
if (q2 == "yes")
{
System.out.println("\nMy guess is that you are thinking of a moose.");
System.out.println("I would ask you if I'm right, but I don't actually care.");
}
}
if(q1 == "vegetable")
{
if (q2 == "no")
{
System.out.println("\bMy guess is that you are thinking of a carrot.");
System.out.println("I would ask you if I'm right, but I don't actually care.");
}
if (q2 == "yes")
{
System.out.println("\nMy guess is that you are thinking of a watermelon.");
System.out.println("I would ask you if I'm right, but I don't actually care.");
}
}
if(q1 == "mineral")
{
if (q2 == "no")
{
System.out.println("\bMy guess is that you are thinking of a paperclip.");
System.out.println("I would ask you if I'm right, but I don't actually care.");
}
if (q2 == "yes")
{
System.out.println("\nMy guess is that you are thinking of a Camaro.");
System.out.println("I would ask you if I'm right, but I don't actually care.");
}
}
}
}
Does anyone know where I went wrong? I don't see it and it should work. I would greatly appreciate any sort of input or advice you may have.
2
Upvotes
View all comments
Show parent comment
1
u/XmasJones Mar 02 '13
How does one correct the problem of capitalization? So if they were to type "Yes" rather then "yes". Is there a way to convert the string to all upper case or lower for the program behind the scenes after the user has typed it in? Thanks!