gpt4 book ai didi

java - 如何在Android应用程序中只制作一次随机数?

转载 作者:太空狗 更新时间:2023-10-29 15:45:55 25 4
gpt4 key购买 nike

我正在开发一个“猜数字”应用程序,它会生成一个介于 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" );
}


}

最佳答案

在您的类中创建 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);

关于java - 如何在Android应用程序中只制作一次随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27994810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com