2017-02-11 41 views
0

我已经发布此代码之前,但这是一个不同的问题。Android应用程序保持随机数字相同

当按下'猜测'按钮时,会产生一个随机数。代码的唯一问题就是它每次都会生成一个新号码,而不管用户是否猜对了正确的号码。理想情况下,我想给用户3个猜测限制,这将需要应用程序保持生成的随机数字相同,然后在3次不正确的尝试后重置。我已经陷入了僵局,因为我很久没有做任何java了,并且把它融入到这个应用程序中让我感到困惑。

在此先感谢

package lab.mad.cct.c3375331task1; 

import android.content.DialogInterface; 
import android.graphics.Color; 
import android.os.Bundle; 
import android.support.v7.app.AlertDialog; 
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().to String()); 
       int attempts = 0; 


       if (userNumber >19) { 
       guessText.setText("Please guess between 0 and 20"); 
       } else if (userNumber == ranNum) { 
        guessText.setText("You got it!"); 
       } 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!"); 
       } 

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

       userGuess.setText(""); 

      } 
     }); 

    } 



} 
+0

不要选择'新的随机()'在循环内。它每次都将序列重置到同一点。 –

回答

0

onClick(View v)删除int userNumber = Integer.parseInt(userGuess.getText().to String());因为每次guessme按钮被按下,就会产生新的号码。

+0

从字面上只删除它,它会保持相同的数字? –

+0

如果我把这条线,这使得我的if-else语句不存在 –

0

声明一些变量,类

public static final int ATTEMPTS = 3; 
public int attempt = 0; 
public int currentRandomNumber = new Random().nextInt(5); 

内部的onClick();

if(attempt >= ATTEMPTS){ 
    attempt = 0; 
    currentRandomNumber = new Random().nextInt(5); 
} else { 
    attempt++; 
} 

// the rest of your code.. 

还,您使用的rand..nextInt(5),但是你的代码的样子,你应该使用..nextInt(20)

+0

哦,大声笑我把它改为5用于测试目的。当我开心的时候它会是20。感谢代码的其余部分。我会给它一个旋转,让你知道 –