vendredi 16 janvier 2015

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

I'm developing a "guess the number" app, it generates a random number between 1 and 10,000 and you have to try guessing, it will tell you if your prediction it is too big , etc But when you press the button to probe your number, it generates a new random number every time you press the button.Keep in mind i'm a newbie so i'm learning java for android, but i want to know how to make this simple app.


Here's my code:



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


}


}





Aucun commentaire:

Enregistrer un commentaire