【发布时间】:2014-03-12 22:37:52
【问题描述】:
我正在尝试制作一个简单的程序,该程序将显示 20 个介于 1 和 100 之间的随机数,然后打印出哪些数字可以被 3 整除并等于 1%3 和 2%3。它似乎工作得很好,但我注意到它只适用于列表中的最后一个数字。在搜索我的数学时,我缺少什么来包含所有数字?提前感谢您为我提供的任何帮助!
import java.util.Random;
public class Lab5 {
public static void main(String[] args) {
Random rnd = new Random();
int repeat = 19;
int n = 0;
for(int i=0;i<=repeat;i++){
n = rnd.nextInt(100)+1;
System.out.print(n+", ");
}
System.out.println();
System.out.println("-------------------------------------");
if(n % 3 == 0){
System.out.println("Numbers divisible by three: "+n+(", "));
}else{
System.out.println("Numbers divisible by three: NONE");
}
System.out.println("-------------------------------------");
if(n == 1 % 3){
System.out.println("Numbers equivalent to one modulo three: "+n+(", "));
}else{
System.out.println("Numbers equivalent to one modulo three: NONE");
}
System.out.println("-------------------------------------");
if(n == 2 % 3){
System.out.println("Numbers equivalent to two modulo three: "+n+(", "));
}else{
System.out.println("Numbers equivalent to two modulo three: NONE");
}
}
}
【问题讨论】:
-
您正在执行
for循环的 20 次迭代,每次都计算 n。然后,在 for 循环终止后,执行if块。您需要在 for 循环中执行数学运算。 -
或者,将数字存储到数组(或集合)中,然后对数组中的值进行数学运算。
标签: java for-loop random division modulo