使用随机整数

时间:2014-12-24 23:02:21

标签: java random

这是作业: 对于这个程序,有两个“部分”。第一部分将进行试验并确定每个试验在找到获胜上限之前打开的盖帽数量。每个试验(人)都将成为胜利者。每个试验打开的上限数量将写入文件。 程序的第二部分将读取值并计算平均值。平均值应在4.5到5.5之间,因为获胜的几率为1/5。

它编译并运行,但平均值始终为0.

我的代码:

  int randNum = 0; 
  Random randNumList = new Random(); 

  int counter = 0;
  Scanner in = new Scanner(System.in);
  System.out.println("How many trials will there be?");
  int trials = in.nextInt();

  int winner = 0;

  PrintWriter outFile = new PrintWriter (new File("cap.txt")); 
  //run trials
  for (int loop = 1; loop <= trials; loop++)    
  {  
    //select random number until 5 is selected
    randNum = randNumList.nextInt(6);
    for (randNum = randNumList.nextInt(6); randNum == 5; randNum++)
    { 
      randNum = randNumList.nextInt(6);
      counter++;
    }

    outFile.println(loop + " " + randNum);
  }   


  outFile.close ( );    //close the file when finished 

  String token = " ";
  Scanner inFile = new Scanner(new File("cap.txt")); 

  while (inFile.hasNext())
  {      
       token = inFile.next();
       if(token.equals("5"))
         winner++;  
  }

  double average = winner/counter;
  System.out.println("The average number is " + average);

3 个答案:

答案 0 :(得分:0)

您的cap.txt文件不包含&#34; 5&#34; =&GT;胜利者= 0,平均值= 0 /计数器= 0(总是)。

答案 1 :(得分:0)

winner/counter返回一个int而不是double(整数除法,因为两个操作数都是整数,因此结果被截断)。试试这个:

winner/(double)counter

确实会返回双倍。

答案 2 :(得分:0)

除了int / int除法准确性问题,应该winner/(double)counter(double)winner/counter尝试将内部for loop更改为do while。通常,当您不知道确切的迭代次数时,请更喜欢while

此外,randNumList.nextInt(6)为[0-5],因此有6种可能的结果 - &gt; 1/6获胜机会。要更正此问题,请使用randNumList.nextInt(5)+ 1

for (int loop = 1; loop <= trials; loop++) {  
    //select random number until 5 is selected
    do {
        randNum = randNumList.nextInt(5) + 1;
        counter++;
    } while (randNum != 5);

    outFile.println(loop + " " + randNum); //why here?? maybe you should add it below counter++;
}  

if(token.equals("5"))也不起作用,因为您编写(loop + randNum),如果您使用outFile.println(randNum);

,它应该可以正常工作