我正在学习自己使用Java和代码,我是网络技术,并想学习如何编码。我正在从一个名为编程的网站上学习,我被困在一项任务上:
https://programmingbydoing.com/a/twenty-questions.html
下面是我的代码,它会编译,但问题是嵌套if语句不能正常工作请帮助!!!
import java.util.Scanner;
public class twentyQuestions
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String question1, question2, guess;
System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I will try to guess it.");
System.out.println();
System.out.println("Question 1: Is it an animal, vegetable, or mineral?");
question1 = keyboard.next();
System.out.println();
System.out.println("Question 2: Is it bigger than a bread box?");
question2 = keyboard.next();
if (question1.equals("animal"))
{
if (question2.equals("no"))
{
guess = "squirrel";
}
else {
guess = "moose";
}
}
else if (question1.equals("vegetable"))
{
if (question2.equals("no"))
{
guess = "carrot";
}
else
{
guess = "watermelon";
}
}
else if (question1.equals("mineral"));
{
if (question2.equals("no"))
{
guess = "paper clip";
}
else
{
guess = "Camaro";
}
}
System.out.println("You're thinking of a " + guess);
}
}
}
答案 0 :(得分:1)
首先,您需要在
之后删除分号else if (question1.equals("mineral"))
然后,您需要在else
语句的末尾添加最后的if
块,以捕获与三个输入中的任何一个都不匹配的输入。然后它就可以编译:
...
else if (question1.equals("mineral"))
{
if (question2.equals("no")) {
guess = "paper clip";
} else {
guess = "Camaro";
}
}else{
System.out.println("Invalid input");
return;
}
...
答案 1 :(得分:0)
谢谢你们这里是我最后的代码,感谢所有人......: import java.util.Scanner;
公共课二十问题 { public static void main(String [] args) { 扫描仪键盘=新扫描仪(System.in); 字符串question1,question2,guess =“”;
System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I will try to guess it.");
System.out.println();
System.out.println("Question 1: Is it an animal, vegetable, or mineral?");
question1 = keyboard.next();
System.out.println();
System.out.println("Question 2: Is it bigger than a bread box?");
question2 = keyboard.next();
if (question1.equals("animal"))
{
if (question2.equals("no"))
{
guess = "squirrel";
}
else {
guess = "moose";
}
}
else if (question1.equals("vegetable"))
{
if (question2.equals("no"))
{
guess = "carrot";
}
else
{
guess = "watermelon";
}
}
else if (question1.equals("mineral"))
{
if (question2.equals("no"))
{
guess = "paper clip";
}
else
{
guess = "Camaro";
}
}
else{
System.out.println("Invalid input");
return;
}
System.out.println("You're thinking of a " + guess);
}
}