首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >程序掷骰子的次数(使用数组),并且必须显示掷骰子的次数(除非它不起作用)

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

Stack Overflow用户
提问于 2013-03-20 07:32:13
回答 1查看 3.9K关注 0票数 0

我的程序的目标是掷出两个六面骰子,然后将两个骰子相加(1000次),并打印出程序中掷出的数字'4‘的多少倍。我尝试在循环外部和内部使用math.random类,没有明显的区别,甚至一开始也没有使用for循环,我的目标是最终将输出调用到main方法,以便打印它。我听到的count4++可以用于这样的操作,除了一些错误导致我使用它。任何帮助、指导或建议都将不胜感激。我真的很抱歉没有最好的代码编写格式,技能,或常识,请注意,这是我第一年采取编程。我收到错误count4++;cannot be resolved,修复它的唯一方法是将它设置为0,这会毁掉我的程序,因为它总是打印0。

代码语言:javascript
运行
复制
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??
  }
}
} }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-20 07:45:28

您没有初始化本地变量count4 -这是必须完成的。在循环之前,您可以使用:int count4 = 0;。一个方法中的局部变量与另一个方法中的局部变量不同,所以我建议您将input()方法中的count4变量返回给main方法,并将其打印出来。

你也没有按照你期望的那样计算掷骰子,这意味着你永远得不到4的和。Math.random()返回一个介于0和1(独占)之间的随机数-所以你的骰子将是:(int) (0-0.999)*2+4=(int)(0-1.999)+4=(int)4-5.9999= 4-5。相反,请使用(int)Math.random()*6+1

编辑:

代码语言:javascript
运行
复制
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;
} 
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15512512

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档