如何在 android 应用程序中只生成一次随机数?

How to make a random number only once in an android app?

我正在开发一个 "guess the number" 应用程序,它会生成一个介于 1 到 10,000 之间的随机数,你必须尝试猜测,它会告诉你你的预测是否太大,等等 但是当你按下按钮来探测你的号码时,它会在你每次按下 button.Keep 时生成一个新的随机数 我是新手所以我正在学习 java for android , 但我想知道如何制作这个简单的应用程序。

这是我的代码:

package com.boodle.guessthenumber;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {


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


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
public void guess (View view){

    EditText textguess = (EditText) findViewById ( R.id.textguess );

    TextView resulta = (TextView) findViewById(R.id.resulto);

    String guessStr = textguess.getText().toString();

    int theGuess = Integer.parseInt(guessStr);

    int rand = (int) (Math.random()*10000+1);

    if (theGuess > rand) {
        resulta.setText(textguess.getText() + " is too big" );
    }

    if (theGuess < rand) {
        resulta.setText(textguess.getText() + " is too small" );
    }

    if (rand == theGuess){
        resulta.setText(textguess.getText() + " is the answer" );
    }


}

}

在 class:

中创建 rand 作为成员变量
public class MainActivity extends ActionBarActivity {

    int rand;

在 onCreate() 中初始化:

rand = (int) (Math.random()*10000+1);

删除 guess() 函数中的初始化:

// not needed anymore:
// int rand = (int) (Math.random()*10000+1);

要使数字在方向更改期间保持不变,请将此代码添加到您的 Activity:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putInt("rand", rand);
    super.onSaveInstanceState(savedInstanceState);
}

然后在 onCreate() 中将您的随机数生成代码更改为:

if (savedInstanceState != null)
    rand = savedInstanceState.getInt("rand");
else
    rand = (int) (Math.random()*10000+1);

生成数字后,您必须将其存储在持久存储中,为此您有很多选择:SharedPreferences(可以在活动之间传递)、文件、SQLiteDatabase...

当 activity 开始时,仅当数字不存在时 - 生成它!

解决方案是在 onCreate 中创建您的随机数,这样它只创建一次,然后只需在您的 guess 方法中访问该变量。修改您的代码如下:

public class MainActivity extends ActionBarActivity
{

    private int rand;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);
        rand = (int) (Math.random()*10000+1);
    }

    // rest of code...

然后在 guess 中删除初始化并简单地按名称访问变量:

public void guess (View view)
{
    // rest of code...

    //int rand = (int) (Math.random()*10000+1);

    if (theGuess > rand) {
        resulta.setText(textguess.getText() + " is too big" );
    }

    // rest of code...
}

另外,请注意,没有必要 post 所有 import 语句和其他类似代码。只有 post输入与您的问题相关的代码是获得简洁答案的最佳方式。

以下解决方案将在 activity 启动时生成数字,并且当用户旋转屏幕时数字不会改变。它还将使 activity 更有效一些。

public class MainActivity extends ActionBarActivity {

  TextView mResult;
  EditText mTextGuess;

  private int mNumber;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_main);
    // you find your views in onCreate once, they don't change, it's effective
    mResult = (TextView) findViewById(R.id.resulto);
    mTextGuess = (EditText) findViewById(R.id.textguess);
    // BRO-TIP: Google "Butterknife".

    // Now you need to initialize the random number
    // BUT you want it to stay the same when user rotates the screen, right?
    if (savedInstanceState == null) {
      // when the user first opens the app, generate new number
      mNumber = (int) (Math.random()*10000+1);
    } else {
      // otherwise load the previously generated number from saved state
      mNumber = savedInstanceState.getInt("mNumber");
    }
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    // here you save the number across orientation changes
    outState.putInt("mNumber", mNumber);
  }

  public void guess(View v) {
    int theGuess = Integer.parseInt(mTextGuess.getText().toString());

    // else-if is better for you: when the first is true, you don't need to check the others and so on... 
    if (theGuess > rand) {
      mResult.setText(textguess.getText() + " is too big" );
    } else if (theGuess < rand) {
      mResult.setText(textguess.getText() + " is too small" );
    } else if (rand == theGuess){
      mResult.setText(textguess.getText() + " is the answer" );
    }
  }
}