我正在一個骰子滾動項目上工作,有點卡住了。我仍然不熟悉Java編程和使用數組,所以我敢肯定我搞砸了一些東西。最終目標是輸出一個包含擲骰數量(我有和正在使用的數量)的表格,然後根據擲骰子擲出的擲骰數量加起來的骰子總數。表格工作正常,但我無法獲得總和。如果我擲4骰子,我仍然可以得到1-3。任何人都可以給我一個領導與合作?我卡住了! ):爪哇:骰子滾動和不正確的總和
import javax.swing.*;
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();
private final static int FACENUMBER = 6;
private static int faceValue = 1;
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);
System.out.println();
int total[] = new int[(M) + 1];
for (int roll = 1; roll <= M; roll++) {
total[roll] = rnd.nextInt(FACENUMBER * N) + 1;
}
System.out.printf("%3s%12s\n", "Rolls", " Sum of Rolls");
for (int k = 1; k < total.length; k++) {
System.out.printf("%3s%12s\n", k, total[k]);
}
}
}
數組由索引進行尋址。例如總計[指數]。在Java中,索引值從零開始(0)。你的循環「(int roll = 1 ...」跳過第一個值 – DwB
@DwB:如果不是故意的,這個處理似乎是用'new int [(M)+1]'和roll <= M '提醒我BASIC。 –
如果OP有意從1開始,那麼這是錯誤的:「int k = 1; k
DwB