程序滚动骰子次数(使用数组),并且必须显示数字滚动的次数(除非它不起作用))

时间:2013-03-19 23:32:13

标签: java arrays methods

我的程序的目标是滚动两个六面骰子,然后添加两个,(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??
  }
}
} }

1 个答案:

答案 0 :(得分:2)

您没有初始化本地变量count4 - 必须完成。在循环之前,您可以:int count4 = 0;。一个方法中的局部变量与另一个方法中的局部变量不同,因此我建议您将count4变量从input()方法返回到main方法,然后将其打印出来。 / p>

你也没有像你想象的那样计算掷骰子,这意味着你永远不会得到4的总和。Math.random()会返回0到1之间的随机数(不包括) - 所以你的die将是:(int)(0-0.999)* 2 + 4 =(int)(0-1.999)+ 4 =(int)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;
}