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

时间:2015-01-17 00:20:44

标签: java android random numbers

我正在开发一个“猜数字”应用程序,它会生成1到10,000之间的随机数,你必须尝试猜测,它会告诉你你的预测是否太大,等等 但是当你按下按钮来探测你的号码时,每次按下按钮都会产生一个新的随机数。请记住我是新手,所以我正在学习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" );
    }


}

}

4 个答案:

答案 0 :(得分:5)

在您的班级中将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);

要在方向更改期间保持号码,请将此代码添加到您的活动:

@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);

答案 1 :(得分:2)

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

当活动开始时,只有当数字不存在时 - 生成它!

答案 2 :(得分:1)

解决方案是在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...
}

另外,就像注释一样,没有必要发布所有import语句和其他类似代码。只发布与您的问题相关的代码是邀请简明答案的最佳方式。

答案 3 :(得分:1)

以下解决方案将在活动开始时生成数字,并且当用户旋转屏幕时数字不会更改。它还可以使活动更有效。

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" );
    }
  }
}