简单的初学者Java问题。我刚刚学会了如何使用数组,这对我来说仍然有点混乱。我的目标是简单地滚动一些骰子,然后将其作为总和,频率和百分比投影。我确定我做的事情很愚蠢,但我忽略了它!
import javax.swing.JOptionPane;
import java.util.Random;
public class Lab1 {
private static int N = 0;
private static int M = 0;
private static int total = 0;
private static Random rnd = new Random();
public Lab1(){
}
public static void main(String[] args) {
N = Integer.parseInt(JOptionPane.showInputDialog("How many dice would you like to roll?"));
System.out.println("Dice: "+N);
M = Integer.parseInt(JOptionPane.showInputDialog("How many times would you like to roll?"));
System.out.println("Rolls: "+M);
int total[] = new int[(6*Lab1.N)+1];
for (int i=0; i<=total.length; i++)
total[i] = 0;
for (int roll=1; roll<=M; roll++){
N = 1+rnd.nextInt(6);
total[N]++;
}
System.out.printf("%3s%12s%12s\n", "Sum","Frequency", "Percentage " );
for(int k=2; k<total.length; k++);{
int percent = total[k]/(360);
System.out.printf("%3s%12s%12s\n", k, total[k], percent);
}
}
}
答案 0 :(得分:2)
从我所看到的问题是你如何存储骰子的先前角色。我相信你的问题在于这个方法:
for (int roll=1; roll<=M; roll++){
N = 1+rnd.nextInt(6);
total[N]++;
}
我会将此更改为
for (int roll=1; roll<=M; roll++){
total[roll] = rnd.nextInt(6);
}
这会建立一个存储每个骰子卷的数组 - 如果这当然是你要找的......
答案 1 :(得分:1)
for(int k=2; k<total.length; k++);{
您需要从循环中删除;
符号,因为当您终止它时,'k'将不会在循环中解析。格式为for(x, x, x) {
接下来要看的是:
骰子:1
劳斯:1
线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:7 在Lab1.main(Lab1.java:26)
提示:
total[i] = 0; // this line is the problem.
查看循环中的<=
。
for (int i=0; i<total.length; i++)
简单地将其添加到<
会产生以下结果:
骰子:1
劳斯:1
总和频率百分比
2 1 0
3 0 0
4 0 0
5 0 0
6 0 0
答案 2 :(得分:1)
两件事。
首先,这个循环将不可避免地抛出ArrayIndexOutOfBoundsException
(“元素”total[total.length]
超出范围)
for (int i=0; i<=total.length; i++)
total[i] = 0;
您应该使用<
代替<=
。
for (int i=0; i<total.length; i++)
total[i] = 0;
其次,这一行:
for(int k=2; k<total.length; k++);{
这里有一个空循环。您应该在{
:
for(int k=2; k<total.length; k++){
现在你的代码编译,不会在开始时抛出异常,并打印一个漂亮的表。 这是一个开始。