代码有什么问题? [英] What is wrong with the code?

查看:73
本文介绍了代码有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Using the Die class defined in Chapter 4, write a class called PairOfDice, composed of two Die objects. Include a constructor, methods to set and get each of the individual die values, a method to roll the two die, and a method that returns the current sum of the two die values.





我尝试了什么:





What I have tried:

public class PairOfDice {
    Die die1 = new Die();
    Die die2 = new Die();
    
    public int getDie1Value() {
        return die1Value;
    }
    public int getDie2Value() {
        return die2Value;
    }
    public void setDie1Value(int die1) {
        die1Value = value;
    }
    public void setDie2Value(int die2) {
        die2Value = value;
    }
    public PairOfDice() {
        roll();
    }
    public int total() {
        return die1+die2;
}
}

推荐答案

你的set方法试图设置(并获取)一个不是的变量任何地方定义您应该使用单个Die对象的 setFaceValue getFaceValue 方法。



[edit]

另外,你的构造函数调用 roll 方法,而不是创建两个骰子,而 roll 方法未在任何地方定义,因此会导致问题。最后,你的总计方法试图将两个Die对象加在一起,而不是它们的值。

[/ edit]
Your set methods are trying to set (and get) a variable that is not defined anywhere. You should be using the setFaceValue and getFaceValue methods of your individual Die objects.

[edit]
Also, your constructor calls the roll method, rather than creating the two dice, and the roll method is not defined anywhere so that will cause problems. Finally, your total method is trying to add the two Die objects together, rather than their values.
[/edit]


尝试满足要求:

Try to satisfy the requirements:
public class PairOfDice
{
  Die die1, die2;

  public PairOfDice()
  {
    die1 = new Die();
    die2 = new Die();
  }

  public int getFirstDieFaceValue()
  {
    return die1.getFaceValue();
  }

  public int getSecondDieFaceValue()
  {
    return die2.getFaceValue();
  }

  private int clamp(int value)
  {
    if ( value < 1) // here a public Die.MIN would have been useful
      value = 1;
    else if (value > 6) // here a public Die.MAX would have been useful
      value = 6;
    return value;
  }

  public void setFirstdDieFaceValue(int value)
  {
    die1.setFaceValue(clamp(value));
  }
  public void setSecondDieFaceValue(int value)
  {
    die2.setFaceValue(clamp(value));
  }

  public int roll()
  {
    return ( die1.roll() + die2.roll());
  }

  public int sumOfValues()
  {
    return (die1.getFaceValue() + die2.getFaceValue());
  }
  public static void main( String arg[] )
  {
    PairOfDice pod = new PairOfDice();
    System.out.printf("rolling the dices...\nResult = %d\n", pod.roll());
  } 
} 


这篇关于代码有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆