所以我试图制作一个程序,为学校提出两个问题。我遇到的问题是当我只想要一个时,java会不断打印多条消息。 any
是否可以告诉我该怎么做?这是代码:
if (answer1.equals("inside") ||
answer1.equals("outside") ||
answer1.equals("both") )
System.out.println("Question 2) Is it a living thing?(yes/no)");
answer2 = keyboard.next();
if (answer2.equals("yes") )
System.out.println("Then what else could you be thinking of besides a houseplant?!");
if (answer2.equals("no") )
System.out.println("Then what else could you be thinking of besides a shower curtain?!");
if (answer2.equals("yes") )
System.out.println("Then what else could you be thinking of besides a bison?!");
if (answer2.equals("no") )
System.out.println("Then what else could you be thinking of besides a billboard?!");
if (answer2.equals("yes") )
System.out.println("Then what else could you be thinking of besides a dog?!");
if (answer2.equals("no") )
System.out.println("Then what else could you be thinking of besides a cell phone?!");
}
}
答案 0 :(得分:0)
您可以使用switch语句来完成此操作,而无需使用if / else语句。但是,如果没有像在问题中那样打印出多条消息,则无法在多个if语句中检查“是”和“否”。
创建一个参数设置为answer2.toUpperCase()的开关,这样每个答案都可以正常工作,忽略大小写。
如果大小写等于参数,开关将执行案例中的所有内容。结束每个案例添加“休息”;最后。
switch(answer2.toUpperCase()) {
case "YES":
System.out.println("What else could you be thinking of besides a houseplant?!");
break;
case "NO":
System.out.println("Then what else could you be thinking of besides a shower curtain?!");
break;
//And add the rest here
}
答案 1 :(得分:0)
仅使用if语句来检查某些内容。
逻辑(注意:不是确切的代码,只有逻辑):
//may use a while loop asking the question until a desired answer
System.out.println("(Question 1) Is it a living thing?(yes/no)");
String answerOne = //get user input;
System.out.println("(Question 2) Is it a dead thing?(yes/no)");
String answerTwo = //get user input;
if (answerOne.equals("yes") && answerTwo.equals("no") ) {
System.out.println("it is a living thing!");
}
if (answerOne.equals("no") && answerTwo.equals("yes") ) {
System.out.println("its DEAD!");
}