Jump to content

Recommended Posts

Posted

Boas!

Estou a trabalhar num pequeno projecto para a minha escola em que tenho que criar uma aplicação Android que me sorteie 5 números de 1 a 50 de modo a que nunca se repitam.

Já consegui ter os 5 números a sortear. mas estou com algumas dificuldades em fazer com que não se repitam..

Será que alguem me pode dar uma ajudinha?

public class MainActivity extends Activity {
int counter;
Button button1;
TextView display1, display2, display3, display4, display5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
display1 = (TextView) findViewById(R.id.tvDisplay1);
display2 = (TextView) findViewById(R.id.tvDisplay2);
display3 = (TextView) findViewById(R.id.tvDisplay3);
display4 = (TextView) findViewById(R.id.tvDisplay4);
display5 = (TextView) findViewById(R.id.tvDisplay5);
button1.setonclickListener(new View.onclickListener() {
@Override
public void onclick(View v) {
// TODO Auto-generated method stub


Random gen1 = new Random();
int random1 = gen1.nextInt(50) + 1;
display1.setText(random1);

Random gen2 = new Random();
int random2 = gen2.nextInt(50) + 1;
display2.setText(random2);

Random gen3 = new Random();
int random3 = gen3.nextInt(50) + 1;
display3.setText(random3);

Random gen4 = new Random();
int random4 = gen4.nextInt(50) + 1;
display4.setText(random4);

Random gen5 = new Random();
int random5 = gen5.nextInt(50) + 1;
display5.setText(random5);



}
});

}

Desde já agradeço todas as vossas informações 🙂

Desculpem se a formatação do tópico está mal feita mas sou novo por aqui 🙂

Posted

Usa um ArrayList e Integers:

List<Integer> numeros = new ArrayList<Integer>();

for (int i = 1; i <= 50; i++)
   numeros.add(i);

Escolhes uma casa aleatóriamente e removes:

int random = numeros.remove( gen.nextInt( numeros.size() ) );

“There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.”

-- Tony Hoare

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.