2013-10-28 40 views
0

我是新來的Java和學習 - 所以請原諒這可能是愚蠢的問題!不兼容類型的問題

它...

使用一個簡單的紙岩石剪刀遊戲的BlueJ我不斷收到此錯誤;

「不兼容類型」

運行此代碼時;

import comp102.*; 

import java.util.Scanner; 


public class RPS{ 

    String paper = "paper"; 
    String rock = "rock"; 
    String scissors = "scissors";  

public void playRound(){ 

     String paper = "paper"; 
     String rock = "rock"; 
     String scissors = "scissors";  

     System.out.print ('\f'); // clears screen 
     Scanner currentUserSelection = new Scanner(System.in); 

     String enterText = null; 
     System.out.println("Make your Selection; Paper, Rock or Scissors: "); 
     enterText = currentUserSelection.next(); 

     System.out.println("enterText = " + enterText); 

     if(enterText = paper){ 
      System.out.println("the IF Stmt is working"); 
     } 

    } 

錯誤指的是這條線, 「如果(enterText =紙){」

非常感謝

+0

感謝您的幫助:-) –

+0

不客氣。如果您的問題已解決,您可以將以下答案中的一個標記爲已接受,請參閱此鏈接[接受答案如何工作?](http://meta.stackexchange.com/q/5234/203266) –

回答

0

使用

if(enterText == paper) 

代替

0

更改您if{..}條件as

if(enterText.equals(paper)){ 
    System.out.println("the IF Stmt is working"); 
} 

因爲您正在if條件中分配值。所以它是無效的。

內,如果條件你必須檢查它要麼是只。

if語法if(){..}

if(true or false) { 
    //body 
} 
1

您試圖分配值這是不允許的

if(enterText = paper) //here if expects expression which evaluates to boolean 

更改爲,

if(enterText == paper) 

language specs jls-14.9

if語句允許條件執行語句或兩個語句的條件選擇,執行一個或另一個,但不能同時執行。

表達式必須具有布爾類型或布爾類型,否則會發生編譯時錯誤。

代替==操作者使用String#equals比較字符串。

if(enterText.equals(paper)) //this will compare the String values 

0
if(enterText = paper){ 
      System.out.println("the IF Stmt is working"); 
} 

見你應該使用==檢查是否相等。但是由於您正在處理字符串,因此使用equals()方法

例如,

if(enterText.equals(paper)){ 
     System.out.println("the IF Stmt is working"); 
} 
0
if(enterText = paper){ 
    System.out.println("the IF Stmt is working"); 
} 

這裏使用的是=這是賦值運算符。

其中==檢查是否相等。

更多在Java中,檢查字符串平等的,你應該使用equals()

原因:Why doesn’t == work on String?

所以,你的代碼變得,

if(enterText.equals(paper)){ 
     System.out.println("the IF Stmt is working"); 
    } 
0
if(enterText = paper){ 
     System.out.println("the IF Stmt is working"); 
    } 

應該

if(enterText == paper){ 
     System.out.println("the IF Stmt is working"); 
    }