所以我应该创建一个程序,生成1到1000之间的100个随机整数,然后告诉返回偶数和奇数的整数。到目前为止,我已经完成了那部分工作。然而,第二部分我无法弄清楚。我需要做同样的事情10次,然后我需要将所有这些加在一起以获得总数。
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);
}
}
我试过拿出
System.out.println("Iteration " + " Evens " + " Odds");
并将其放在while循环上方,然后除去其中一个
iteration++;
System.out.println(iteration + " " + even + " " + odd);
但是当我这样做时,我的平均值和赔率几乎翻倍。
所以重复我想再做的事情:我想每个人都这样做
iteration++;
System.out.println(iteration + " " + even + " " + odd);
显示一个新的偶数和奇数,而不是相同的。然后,由于我不确定如何做到这一点,我想总计十个平均值和十个赔率。谢谢你的帮助!
答案 0 :(得分:4)
你几乎就在那里,主要问题是你在while循环中增加了10次迭代,所以它会立即从while循环中退出。我刚刚删除了所有这些增量,它确实有效!
此外,在while循环外部有一个偶数和奇数的总计数器,然后在while循环中每次迭代后加总,如下所示:
public class EvenOrOdd {
public static void main(String[] args) {
Random random = new Random();
int evenTotal = 0, oddTotal = 0;
int iteration = 0;
System.out.println("Iteration " + " Evens " + " Odds");
while (iteration < 10) {
int even = 0, odd = 0;
for (int i = 0; i < 100; i++) {
int number2 = random.nextInt(1000) + 1;
if ((number2 % 2) == 0)
even++;
else if ((number2 % 2) == 1)
odd++;
}
iteration++;
System.out.println(iteration + " " + even + " " + odd);
evenTotal += even;
oddTotal += odd;
}
System.out.println("\nEvens: " + evenTotal + "\nOdds: " + oddTotal);
}
}