【问题标题】:Trouble instantiating a variable in a Yahtzee scorecard type program在 Yahtzee 记分卡类型程序中实例化变量时遇到问题
【发布时间】:2012-10-17 23:25:06
【问题描述】:

好的,所以我正在为 Yahtzee 游戏编写程序,我试图弄清楚如何将每一轮的值存储在该轮记分卡框中,并继续填写记分卡的其他部分。我这样做的方式是通过我的代码的这一部分:

  public static void finalScoreCard(int choice, int points)
  {
 int ones = one(choice, points);
 int twos = two(choice, points);
 int threes = three(choice, points);
 int fours = four(choice, points);
 int fives = five(choice, points);
 int sixes = six(choice, points);
 int threeKind = nine(choice, points);
 int fourKind = ten(choice, points);
 int fullHouse = eleven(choice, points);
 int smallStr = twelve(choice, points);
 int largeStr = thirteen(choice, points);
 int yahtzee = fourteen(choice, points);
 int chance = fifteen(choice, points);
}

 public static int one(int choice, int points)
 {
final int score;
if (choice == 1)
    score = points;

if (choice != 1 && score != points)
    return 0;
else
    return score;
 }

所以“one”方法应该接受选择数和点参数,然后如果选择了该框,则返回分数。 如果用户选择该选项,我希望我的程序实例化“score”,并用“points”分配“score”。然后在他们完成此操作后,该方法应该在每轮之后返回分数,或者返回 0 直到“分数”被实例化。问题是,我不明白如何多次保存“分数”的值。整个程序处于一个运行 13 次的 for 循环中。 谢谢

【问题讨论】:

  • 您希望我们为您编写代码吗?
  • 这应该被标记为家庭作业吗?
  • 您总是可以将score 声明为静态类变量。 private static int score;我不确定你是否在问这个问题……老实说,这是一个非常令人困惑的问题。
  • @CookieOfFortune 作业标签已弃用。 (家庭作业问题仍然是允许的,但它们仍然必须遵循所有好的问题准则)
  • @AndrewBarber 谢谢,很高兴知道。

标签: java variables constants


【解决方案1】:

我会考虑使用一种方法和一个开关。

public void doSomething(int choice, int points)
{
  switch(choice)
  {
    case 1:
      ...
      break;
    case 2:
     ...
     break;
    default:
     //handle default case
  }
}

哦,让score 成为私有变量。假设方法和变量在同一个类中应该没问题。

private int score ;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 2020-01-05
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多