我正在寻求一些帮助。我坐在家里试图从programmingbydoing.com学习java编程。我需要制作一个名为TwentyQuestions的程序。代码缺少一些东西,使它完全工作。 我试图在网上找到其他地方的帮助。这就是为什么代码看起来很像其他人的代码。
import java.util.Scanner;
public class TwentyQuestions
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
String type, size, guess = "";
System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I'll try to guess it.");
System.out.println("");
System.out.println("Question 1) Is it animal, vegetable or mineral?");
System.out.print("> ");
type = keyboard.next();
System.out.println("");
System.out.println("Question 2) Is it bigger than a breadbox?");
System.out.print("> ");
size = keyboard.next();
System.out.println("");
if (type.equalsIgnoreCase("animal"))
{
if (size == "no")
{
guess = "squirrel";
}
else
{
guess = "moose";
}
}
else if (type.equalsIgnoreCase("vegetable"))
{
if (size == "no")
{
guess = "carrot";
}
else
{
guess = "watermelon";
}
}
else if (type.equalsIgnoreCase("mineral"))
{
if (size == "no")
{
guess = "paper clip";
}
else
{
guess = "Camero";
}
}
if (guess == "")
{
System.out.println("The answers provided are not valid. Please try again.");
}
else
{
System.out.println("My guess is that you are thinking of a " + guess + ".");
System.out.println("I would ask you if I'm right, but I don't actually care.");
}
}
}
问题是程序不关心嵌套if语句中的比较。控制总是转到else
并打印出那个。
答案 0 :(得分:-1)
当您想要比较字符串时,您需要使用 .equals()方法,或者在这种情况下忽略大小写 .equalsIgnoreCase()
尝试下面的代码,您会发现它运行正常。
import java.util.Scanner;
public class TwentyQuestions {
public static void main ( String[] args )
{
Scanner keyboard = new Scanner(System.in);
String type, size, guess = "";
System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I'll try to guess it.");
System.out.println("");
System.out.println("Question 1) Is it animal, vegetable or mineral?");
System.out.print("> ");
type = keyboard.next();
System.out.println("");
System.out.println("Question 2) Is it bigger than a breadbox?");
System.out.print("> ");
size = keyboard.next();
System.out.println("");
if (type.equalsIgnoreCase("animal"))
{
if (size.trim().equalsIgnoreCase("no"))
{
guess = "squirrel";
}
else
{
guess = "moose";
}
}
else if (type.equalsIgnoreCase("vegetable"))
{
if (size.trim().equalsIgnoreCase("no"))
{
guess = "carrot";
}
else
{
guess = "watermelon";
}
}
else if (type.equalsIgnoreCase("mineral"))
{
if (size.trim().equalsIgnoreCase("no"))
{
guess = "paper clip";
}
else
{
guess = "Camero";
}
}
if (guess == "")
{
System.out.println("The answers provided are not valid. Please try again.");
}
else
{
System.out.println("My guess is that you are thinking of a " + guess + ".");
System.out.println("I would ask you if I'm right, but I don't actually care.");
}
}
}