2017-02-11 28 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,这是没有必要的。