Green_Sam Green_Sam - 2 years ago 148
Java Question

Dice roller Java returns less random results

i'm trying to make a little program thar throws "reservaDados" number of dice and compare the "dado" (who is a number between 1-10) to a specified dificulty. Then i want to print the count of the number of exits, fails and ultrafails, but i seem to have a problem with the number of times the loop works, it only prints 9 results and i don't seem to find why, i supose that it has to do something with the counter i?

import java.util.*;

public class ProgramTUI {
public static void main(String[] args) {
Scanner var = new Scanner(;
System.out.print("Cuantos dados lanzas?");
int reservaDados = var.nextInt();
System.out.print("Cual es la dificultad?");
int dificultad = var.nextInt();
int i = 0;
int numero_exitos = 0;
int numero_fracasos = 0;
int numero_pifias = 0;
while (i < reservaDados) {
int dado = (int) (Math.random() * 10) + 1;
if (reservaDados == i) {
System.out.println("Has sacado " + numero_exitos + " exitos, " + numero_fracasos
+ " fracasos, " + numero_pifias + " pifias");
} else if (dado == 1) {
} else if (dado < dificultad) {
} else {

Answer Source

In the last iteration, no more counting is done, only the result is printed. So you effectively miss one iteration.

Could be fixed by removing the first else, or by doing one extra iteration.

But just take the whole result printing out of the loop and place it directly after the loop. That will make the intent of the code much clearer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download