public class Die {
public static void main(String[] args) {
Random r = new Random();
int dieOne=0, dieTwo=0, dieThree=0, dieFour=0, dieFive=0, dieSix=0;
Scanner input = new Scanner(System.in);
System.out.println("How many times would you like the die to roll?: ");
int numRoll = input.nextInt();
for (int i=0; i < numRoll; i++) {
int rNum=r.nextInt(6)+1;
if (rNum==1); {
dieOne++;
}
if (rNum==2); {
dieTwo++;
}
if (rNum==3); {
dieThree++;
}
if (rNum==4); {
dieFour++;
}
if (rNum==5); {
dieFive++;
}
if (rNum==6); {
dieSix++;
}
System.out.println("Number:" + rNum);
}
System.out.println("'1' was rolled:" + dieOne + "times.");
System.out.println("'2' was rolled:" + dieTwo + "times.");
System.out.println("'3' was rolled:" + dieThree + "times.");
System.out.println("'4' was rolled:" + dieFour + "times.");
System.out.println("'5' was rolled:" + dieFive + "times.");
System.out.println("'6' was rolled:" + dieSix + "times.");
}
}
所以如果我运行程序并输入2.我会得到这个:
Number:6
Number:3
'1' was rolled:2times.
'2' was rolled:2times.
'3' was rolled:2times.
'4' was rolled:2times.
'5' was rolled:2times.
'6' was rolled:2times.
但我想要的输出是:
Number:6
Number:3
'1' was rolled:0times.
'2' was rolled:0times.
'3' was rolled:1times.
'4' was rolled:0times.
'5' was rolled:0times.
'6' was rolled:1times.
使用同样的方法解决这个问题是什么?
答案 0 :(得分:0)
您应该在if
if (rNum==1) {
dieOne++;
}
而不是
if (rNum==1); {
dieOne++;
}
此外,您应该使用else
分支或更好地使用数组来解决此类问题