我正在尝试将生成的数字放入特定范围,但它不断给我这个输出:
200 Generated numbers, 10 per line:
99 Numbers from 0-20: 1
Numbers from 20-40: 0
Numbers from 40-60: 0
Numbers from 60-80: 0
Numbers from 80-100: 0
18 Numbers from 0-20: 2
Numbers from 20-40: 0
Numbers from 40-60: 0
Numbers from 60-80: 0
Numbers from 80-100: 0
56 Numbers from 0-20: 3
这是我当前的代码:
import java.util.Random;
public class RandomStats2 {
public static void main(String[] args) {
Random random = new Random ();
int[] num = new int [5];
System.out.println("200 Generated numbers, 10 per line: ");
int numbersOnThisLine = 0;
for(int i = 0; i < 200; i++){
int nextNumber = random.nextInt(101);
System.out.print(nextNumber + " ");
numbersOnThisLine++;
if (numbersOnThisLine == 10){
System.out.print("\n");
numbersOnThisLine = 0;
}
if(i <=21) num[0]++;
else if(i <=41) num[1]++;
else if(i <=61) num[2]++;
else if(i <=81) num[3]++;
else if(i <=100) num[4]++;
System.out.println("Numbers from 0-20: " + num[0]);
System.out.println("Numbers from 20-40: " + num[1]);
System.out.println("Numbers from 40-60: " + num[2]);
System.out.println("Numbers from 60-80: " + num[3]);
System.out.println("Numbers from 80-100: " + num[4]);
}
}
}
我怎样才能解决这个问题?另外,如何在 else if 语句中设置 41-60 之类的范围?