2017-02-11 51 views
-1

我再Android應用划拳限制猜測

試圖限制我的Android猜謎遊戲猜測的數目,但它與事實我想比較兩個整數時,其中一人已被轉換爲奮鬥一個字符串:

while (userGuess != userNumber && ++attempts < maxAttempts) ; 

我不知道如何改變它。

順便說一下,我知道,因爲它代表着我的代碼將直接進入最終的if語句,每當我按下猜測按鈕時,它會說我已經嘗試了3次。

感謝

package lab.mad.cct.c3375331task1; 

import android.graphics.Color; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 

import java.util.Random; 

public class Task1Activity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.task1_layout); 

     final TextView textResponse = (TextView) findViewById(R.id.txtResponse); 
     final TextView guessText = (TextView) findViewById(R.id.txtAnswer); 
     final EditText userGuess = (EditText) findViewById(R.id.etNumber); 

     Button pressMe = (Button) findViewById(R.id.btnGuess); 



     // When the button is clicked, it shows the text assigned to the txtResponse TextView box 
     pressMe.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       String randText = ""; 
       Random randGen = new Random(); 
       int ranNum = randGen.nextInt(5); 
       int userNumber = Integer.parseInt(userGuess.getText().toString()); 
       int attempts = 0; 
       final int maxAttempts = 3; 

       while (userGuess != userNumber && ++attempts < maxAttempts) ; 

       if (userNumber >19) { 
        guessText.setText("Please guess between 0 and 20"); 
       } else if (userNumber == ranNum) { 
        guessText.setText("You did it!"); 
        guessText.setBackgroundColor(Color.WHITE); 
       } else if (userNumber < ranNum) { 
        guessText.setText("Your answer is too low. Guess again!"); 
        guessText.setBackgroundColor(Color.RED); 
       } else if (userNumber > ranNum) { 
        guessText.setText("Your answer is too high. Guess again!"); 
        guessText.setBackgroundColor(Color.RED); 
       } 



       if (attempts == maxAttempts) 
        guessText.setText("You have guessed incorrectly three times. The answer was" + ranNum); 

       randText = Integer.toString(ranNum); 
       textResponse.setText(""); 

       userGuess.setText(""); 

      } 
     }); 

    } 



} 
+0

你得到了什麼確切的錯誤,你可以張貼錯誤跟蹤。 –

+0

當然。它是:運算符'!='不能應用於'android.widget.EditText','int' –

+0

您可以從EditText獲得String值,然後使用Integer.parseInt()與您的int值進行比較。 – algojava

回答

0

運營商 '!=' 不能應用於 'android.widget.EditText', '廉政'。

由於錯誤說userGuessuserNumber不能像下面這樣比較,因爲它們是不同的一個在int等是android.widget.EditText

你應該先使用上userGuessgettext(),然後無論是後來進入String或前轉換成int比較userNumber

試試這個,

while(userGuess.getText().equals(String.valueOf(ranNum) && attempts++ < maxAttempts) 

還宣佈attempts全球,你在每一個不要求點擊重置它。如果您想要執行3次點擊,請移除while loop。也刪除userNumber,這是沒有必要的。