错误:缺少返回语句硬币翻转代码

时间:2016-08-31 05:24:08

标签: java

所以我应该修改一个代码,将一个不公平的硬币翻转100次。如果你得到头(你的机会稍微好一点)并且尾巴损失1美元,你会得到1美元。在每个回合结束时,它应该返回整数奖金的值,直到100翻转结束。我收到以下错误:

CoinFlipExperiment.java:18: error: missing return statement
     }
     ^ 1 error

有人有想法吗?

public class CoinFlipExperiment {

 static public int coinFlipExperiment (){
      int winnings = 0;
      for (int i = 1; i<= 100; i++)  {
           double flip = Math.random();
                if (flip< 0.505) {            //heads
                   winnings = winnings + 1;

                }
                else  {                       //tails
                   winnings = winnings - 1;   

                }
                   System.out.println( winnings );
       }

 }

 public static void main(String[] args)  {
      int amount = coinFlipExperiment ();
           System.out.println ("Win/loss amount: " + amount);
   }
}

2 个答案:

答案 0 :(得分:1)

您在coinFlipExperiment方法中缺少return语句,它必须是:

return winnings ; 
正如我猜的那样。所以试试这个:

static public int coinFlipExperiment (){
      int winnings = 0;
      for (int i = 1; i<= 100; i++)  {
           double flip = Math.random();
                if (flip< 0.505) {            //heads
                   winnings = winnings + 1;

                }
                else  {                       //tails
                   winnings = winnings - 1;   

                }
                   System.out.println( winnings );

       }
      return winnings ; 
 }

 public static void main(String[] args)  {
      int amount = coinFlipExperiment ();
           System.out.println ("Win/loss amount: " + amount);
 }
}

答案 1 :(得分:0)

你的函数coinFlipExperiment返回一个整数,但你没有返回任何东西。

您需要在winnings结束时返回coinFlipExperiment