2015-04-24 29 views
-4

我只是想知道爲什麼這個代碼不會打印答案行時編譯過程中沒有出現錯誤。我做learnjavathehardway(https://programmingbydoing.com/a/two-more-questions.html)的分配#35爲什麼這段代碼在編譯時沒有出現錯誤時不打印答案行?新編程

import java.util.Scanner; 

public class TwoMoreQuestions 
{ 
    public static void main(String[] args) 
    { 
     Scanner keyboard = new Scanner(System.in); 

     System.out.print("Question 1: Does it belong inside or outside or both? "); 
     String q1 = keyboard.next(); 

     System.out.println("Question 2: Is it alive? "); 
     String q2 = keyboard.next(); 

     if((q1.equals("inside"))&&(q2.equals("not alive"))) 
     { 
      System.out.println("Then what else could you be thinking of besides a shower curtain?!?"); 
     } 
     if((q1.equals("inside"))&&(q2.equals("alive"))) 
     { 
      System.out.println("Then what else could you be thinking of besides a houseplant?!?"); 
     } 
     if((q1.equals("outside"))&&(q2.equals("alive"))) 
     { 
      System.out.println("Then what else could you be thinking of besides a bison?!?"); 
     } 
     if((q1.equals("outside"))&&(q2.equals("not alive"))) 
     { 
      System.out.println("Then what else could you be thinking of besides a billboard?!?"); 
     } 
     if((q1.equals("both"))&&(q2.equals("alive"))) 
     { 
      System.out.println("Then what else could you be thinking of besides a dog?!?"); 
     } 
     if((q1.equals("both"))&&(q2.equals("not alive"))) 
     { 
      System.out.println("Then what else could you be thinking of besides a cellphone?!?"); 
     } 
    } 
} 
+2

閱讀文檔如何發佈這裏的問題..這不是一個正確的方式張貼SO –

回答

1

看到您的代碼如果使用使用Scanner.next()方法空格後它不會採取價值。所以,如果你給輸入bothalive沒有任何空間,它會告訴你結果,但如果你故意的空間使用後取值Scanner.nextLine();

見你的代碼和註釋它旁邊

 Scanner keyboard = new Scanner(System.in); 

     System.out.print("Question 1: Does it belong inside or outside or both? "); 
     String q1 = keyboard.next();//will not take any value after space 


      System.out.println("Question 2: Is it alive? "); 
      String q2 = keyboard.next();//will not take any value after space 
//so if you enter "not alive" q2 will store only "not". 
      //String q2 = keyboard.nextLine(); 
// this will take all character even after space 
+0

ohhhh問題,我看到,歡呼的隊友。非常感激! – MBNZ

相關問題