2013-11-05 89 views
0

我在if語句中收到了不兼容的類型錯誤消息。變量「answer」和「input2」都是整數,所以我不確定這兩個變量是不兼容的。任何幫助或見解將不勝感激!If語句中的不兼容類型

public static void addingGame() 
{ 

    System.out.print("\n"); 

    System.out.println("********* Part 2: Adding Numbers **********"); 

    System.out.print("\n"); 

    Scanner inputReader = new Scanner(System.in); 

    System.out.print("Would you like to add some numbers?(y/n)"); 
    String input = inputReader.next(); 

    while (!input.equals("y") && !input.equals("n")) 
    { 
     System.out.print("I need a y/n: "); 
     input = inputReader.next(); 
    }  

    while (input.equals("y")) 
    { 
     Random numberGenerator = new Random(); 
     int randomNumber1 = numberGenerator.nextInt(10); 
     int randomNumber2 = numberGenerator.nextInt(10); 
     int answer = ((randomNumber1) + (randomNumber2)); 
     System.out.print(randomNumber1 + " + " + randomNumber2 + " =: "); 
     int input2 = inputReader.nextInt(); 
     if (answer = input2) 
     { 
      System.out.print("Right! " + answer + " is the answer."); 
     } 
     else 
     { 
      System.out.print("Sorry, " + answer + " is the answer."); 
     } 

     System.out.print("Would you like to play again?(y/n)"); 
     input = inputReader.next(); 
     while (!input.equals("y") && !input.equals("n")) 
     { 
      System.out.print("Sorry - I need a y/n: "); 
      input = inputReader.next(); 
     } 
    }  

    System.out.print("\n"); 

    System.out.print("Thanks - Let's move on to Part 3..."); 

回答

3

您使用賦值運算符=當你想要比較值(==)。更改

if (answer = input2) 

if (answer == input2) 

從一個事實,即分配的結果仍然是一個int,其中作爲if條件需要一個boolean,這==提供附帶的錯誤。

+0

非常感謝!對此,我真的非常感激! – user2930063