【问题标题】:How can I edit my code to include a method [closed]如何编辑我的代码以包含方法[关闭]
【发布时间】:2014-10-16 22:28:43
【问题描述】:

如何编辑我的代码以包含一个名为 rollDice() 的方法,以返回生成的介于 1 和 6 之间的随机整数?谢谢。

这是我当前的代码:

public class CrapsGame {

  public static void main(String[] args) {
      int dice1 = (int)(Math.random()* 6) + 1;
      int dice2 = (int)(Math.random()* 6) + 1;
      int roll = dice1 + dice2;
      System.out.println();
      System.out.print("You rolled "+roll+". ");
      if(roll == 2 || roll == 3 || roll == 12){
         System.out.println("You lose");
      }
      else if(roll == 7 || roll == 11){
          System.out.println("You win");
      }
       else{
         System.out.println("point is "+roll+"\n");
         dice1 = (int)(Math.random()* 6) + 1;
         dice2 = (int)(Math.random()* 6) + 1;
         int roll2 = dice1 + dice2;
         System.out.print("You rolled "+roll2+". ");
         while(roll2 != 7){
            if(roll == roll2){
               System.out.println("You win");
               break;
            }
            else{
               System.out.println("point is "+roll+"\n");
            }
            dice1 = (int)(Math.random()* 6) + 1;
            dice2 = (int)(Math.random()* 6) + 1;
            roll2 = dice1 + dice2;
            System.out.print("You rolled "+roll2+". ");
         }
         if(roll2 == 7){
             System.out.println("You lose");
         }          
      }
   }
}

【问题讨论】:

  • 你可以写这一切,但你不知道如何创建一个方法?而且您还没有通过阅读有关 StackOverflow 的其他问题或其中一千个 Java 教程找到任何帮助?
  • 我目前正在学习方法,我之前已经使用过循环。

标签: java loops methods


【解决方案1】:
public class CrapsGame {

  public static void main(String[] args) {
      int dice1 = rollDice();
      (...)
   }

   private static int rollDice() {
      return (int)(Math.random()* 6) + 1;
   }
}

【讨论】:

  • 那个方法应该是静态的
  • 我不断收到非法开始表达式错误。我不确定我做错了什么。
  • 在主字符串之前添加 rollDice() 方法时,我似乎让它工作了。谁能解释这是为什么?
  • 在某些编程语言中这可能是个问题,但在 Java 中,方法和变量的顺序没有区别。
猜你喜欢
  • 2020-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-02
  • 2010-11-04
  • 2016-09-19
  • 1970-01-01
相关资源
最近更新 更多