0

我的程序的目标是掷两个六面骰子,然后将两个骰子相加(1000 次)并打印出程序中数字“4”掷了多少次。我尝试在循环内外使用 math.random 类,但没有明显区别,甚至没有使用 for 循环开始,我的目标是最终将输出调用到 main 方法以打印它。我听到的 count4++ 将适用于此类操作,除非某些错误导致我反对它。任何帮助、指导或建议将不胜感激。对于没有最好的代码编写格式、技能或一般知识,我深表歉意,请注意,这是我学习编程的第一年。我收到错误 count4++;无法解决,修复它的唯一方法是将其设置为 0,这会破坏我的程序,因为它总是打印 0。

import java.io.*;

public class Delt {


public static void main (String args [] ) throws IOException {

int i; 
int Sixside1;
int Sixside2;
int count4 = 0;
int [] data = new int [1000];
input (data);

System.out.println("The number of times '4' came up in the six sided dices is :" + count4);




}
public static void input (int num []) throws IOException {
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
String input;

System.out.println("Hello and welcome to the program");
System.out.println("In this program two six sided dices will be rolled and one eleven sided dice will be rolled (1000 times each");

System.out.println("The dices will be rolled to determine the odds of how many times the roll 4 comes up on both dies(Press any key to con't) ");
input = myInput.readLine ();



for (int i = 0; i < 1000; i++) 
{
  int Sixside1 = (int) (Math.random ()*(6-4) + 4); 
  int Sixside2 = (int) (Math.random ()*(6-4) + 4); 

  double total = Sixside1 + Sixside2;
  if ( total == 4) {
    // print amount of times 4 shows up in 1000 rolls, ?? 
    count4++;
    //return it to main method??
  }
}
} }
4

1 回答 1

2

您没有初始化局部变量count4- 这是必须完成的。在循环之前,您可以拥有:int count4 = 0;. 一种方法中的局部变量与另一种方法中的局部变量不同,所以我建议您将count4变量从input()方法返回到主方法,然后打印出来。

你也没有像你想象的那样计算骰子,这意味着你永远不会得到 4 的总和。Math.random()返回一个介于 0 和 1 之间的随机数(不包括) - 所以你的骰子将是:(int)( 0-0.999)*2+4=(整数)(0-1.999)+4=(整数)4-5.9999= 4-5。相反,使用(int)Math.random()*6+1.

编辑:

public static void main(String[] args) throws Exception  {
    System.out.println(input());
}

public static int input () throws IOException {
    BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
    System.out.println("Hello and welcome to the program");
    System.out.println("In this program two six sided dices will be rolled and one eleven sided dice will be rolled (1000 times each");

    System.out.println("The dices will be rolled to determine the odds of how many times the roll 4 comes up on both dies(Press any key to con't) ");
    myInput.readLine();
    int count4=0;
    for (int i = 0; i < 1000; i++) 
    {
        if ( (int)(Math.random ()*6+1)+(int)(Math.random ()*6+1) == 4) {
            count4++;
        }
    }
    return count4;
} 
于 2013-03-19T23:45:27.580 回答