我是编码的绝对初学者,我正尝试制作一些可以运行5次的代码,并且每次运行时,它将其生成的内容放入5个不同的变量中,以供以后比较,到目前为止,我已经掌握了,它是这样的代码:当运行一次硬币投掷1000次并跟踪其产生的头和尾的数量时,有什么方法可以让它循环5次,并且每次(例如第一次)将计数存储在不同的变量中循环将把第一个磁头的数量存储到countH中,将第二个磁头的数量存储在一个称为countH2中,还是我必须尝试用一种不同的方式?任何帮助表示赞赏。
问题已解决,谢谢
试试这个:
public class Toss {
public final int HEADS = 0;
static int countH = 0;
static int countT = 0;
static int amount = 0;
private static int side;
public static void flip() {
side = (int) (Math.random() * 2);
}
public String toString() {
String sideName;
if (amount == 1000){
amount = 0;
countH = 0;
countT = 0;
}
if (side == HEADS) {
sideName = "Heads";
countH++;
amount++;
} else {
sideName = "Tails";
countT++;
amount++;
}
return sideName;
}
public static void main(String[] args) {
int[][] x = new int[5][2];
int cnt = 0;
do {
do {
flip();
new Toss().toString();
} while (amount != 1000);
x[cnt][0] = countH;
x[cnt][1] = countT;
cnt++;
} while (cnt < 5);
cnt = 0;
do {
System.out.println(cnt);
System.out.println("Number of Tails: " + x[cnt][0]);
System.out.println("Number of Heads: " + x[cnt][1]);
cnt++;
}while (cnt < 5);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句