2016-11-16 45 views
-5

所以即時嘗試製作一個爲學校提出兩個問題的程序。我所擁有的問題是,當我只想要一個時,java會一直打印多條消息。是any一個能夠告訴我如何做到這一點的權利?下面是代碼:如何讓java只用if語句打印一條消息

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

我不知道我的理解,你總是檢查_same_條件。你想在這裏做什麼? – Tunaki

+0

我試圖做的是讓每個語句打印一個不同的答案,我真的不知道如何做到這一點,而不使用其他,否則如果或嵌套if語句(這是作業的一部分) – jackmasterlooter

+1

'answer2'總是與' 「yes」或「no」,所以如果以前是真的,它將保持爲真,因爲變量沒有改變值。打印不同答案的條件是什麼? – Tunaki

回答

0

您可以使用switch語句來完成這項不使用if/else語句。但是,您不能像在問題中一樣檢查多個if語句中的「是」和「否」,而不打印多條消息。

創建參數設置爲answer2.toUpperCase()的開關,以便每個答案都能正常工作而忽略大小寫。

如果情況等於參數,交換機將執行一個案例中的所有內容。要結束每個案例,請添加「break」。最後。

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 

} 
+0

我的一個建議是,如果您試圖隨機化打印哪些消息(如果answer2爲yes),則可能需要使用Math.random()來隨機選擇響應。 –

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!"); 
} 
+0

根據他在該問題下的評論,部分任務是不使用if else/else或嵌套if語句。 – KyleKW

+0

我想我應該在問題本身中提到這一點,但部分任務是僅在複合條件下使用if語句 – jackmasterlooter

+0

如果我明白你希望做的正確,你是否嘗試過使用'if(answer2。等於(「xx」)&& answer1.equals(「yy」))'? – KyleKW