samedi 21 février 2015

Java: Random Class Advice

So I'm supposed to create a program that generates 100 random integers between 1 and 1000, and then tell the number of integers that returned even and odd. I've got that part down so far. The second part I can't figure out, however. I need to do the same thing 10 times, and then I need to add all of those together to get a total.



import java.util.Random;

public class EvenOrOdd
{
public static void main(String[] args)
{
int even = 0, odd = 0;
int iteration = 0;

while (iteration<10)
{
for(int i = 0; i<100;i++)
{
int number2 = random.nextInt(1000) + 1;
if ((number2 % 2) == 0)
{
even++;
}
else if ((number2 % 2) == 1)
{
odd++;
}

}
System.out.println("Iteration " + " Evens " + " Odds");
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
iteration++;
System.out.println(iteration + " " + even + " " + odd);
}
System.out.println("\nEvens: " + even + "\nOdds: " + odd);
}
}


I've tried taking out the



System.out.println("Iteration " + " Evens " + " Odds");


and placing it above the while-loop, and then removing all but one of the



iteration++;
System.out.println(iteration + " " + even + " " + odd);


But when I do that, my evens and odds nearly double each iteration.


So to repeat what I want to do again: I want to make it so each



iteration++;
System.out.println(iteration + " " + even + " " + odd);


displays a new even and odd, and not the same one. And then, since I am not sure how to do this either, I want to total up the ten evens and the ten odds. Thanks for any help!





Aucun commentaire:

Enregistrer un commentaire