Java setter、getter(掷骰子)

发布于 2024-09-28 08:15:56 字数 746 浏览 0 评论 0原文

我有一些关于java的问题。代码中有两个问题(我将它们作为注释留下)。 另外使用设置和获取方法的目的是什么?您能简单地解释一下吗?我是初学者。谢谢 :)

public class Die
{
   private final int MAX = 6;  
   private int faceValue;  

   public Die()
   {
      faceValue = 1;

      //why do you set the faceValue as 1?
   }

   public int roll()
   {
      faceValue = (int)(Math.random() * MAX) + 1;
      //Why do we use MAX instead of just number 6?

      return faceValue;
   }

   public void setFaceValue (int value)
   {
      if (value > 0 && value <= MAX)
         faceValue = value;
   }

   public int getFaceValue()
   {
      return faceValue;
   }

   public String toString()
   {
      String result = Integer.toString(faceValue);
      return result;
   }
}

I have some questions about java. There are two questions in the code (I left them as comments).
Also what is the purpose of using setting and getting methods? Could you please explain it very briefly. I am a beginner. Thank you :)

public class Die
{
   private final int MAX = 6;  
   private int faceValue;  

   public Die()
   {
      faceValue = 1;

      //why do you set the faceValue as 1?
   }

   public int roll()
   {
      faceValue = (int)(Math.random() * MAX) + 1;
      //Why do we use MAX instead of just number 6?

      return faceValue;
   }

   public void setFaceValue (int value)
   {
      if (value > 0 && value <= MAX)
         faceValue = value;
   }

   public int getFaceValue()
   {
      return faceValue;
   }

   public String toString()
   {
      String result = Integer.toString(faceValue);
      return result;
   }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

心的憧憬 2024-10-05 08:15:56

首先,您应该正确使用代码示例标签,这样读起来很难看。使用 getter/setter 方法将阻止直接访问实例变量。这也称为数据隐藏或封装。至于你的问题,faceValue 被初始化为值 1,你通常在构造函数中进行初始化。第二个问题 Math.random 将生成一个 0-1 之间的数字,将其乘以 6,结果是 0 到 5 之间的数字。因此,您添加 +1 以获得 1-6 的范围。

First of all you should use the code sample tag properly this is ugly to read like that. Using getter/setter methods will prevent the direct access to an instance variable. This is also called data hiding or encapsulation. As for your questions, the faceValue gets initialized with the value 1, you normaly do init things within the constructor. The second question Math.random will generate a number between 0-1 you are multiplying it with 6 which results into a number between 0 and 5. So you add +1 to have the range of 1-6.

庆幸我还是我 2024-10-05 08:15:56

您使用常量(“MAX”)是因为在某些情况下您可能想要更改该值,例如如果您想掷二十面骰子。在这种情况下,您只需要更改一行代码,这样就更容易维护。在这种简单的程序中,这没有多大意义,但在更复杂的项目中,您希望使用常量快速更改某些(固定)值,而无需检查每一行。

Getter 和 Setter 方法在面向对象编程中用于封装变量并提供接口以使其他类可以访问这些变量

You use a constant ("MAX") because on some occasion you might want to change the value, for example if you want to roll a twenty-sided dice. In that case you only need to change the code in one line which makes it easier to maintain. It doesn't make THAT much sense in this simple kind of program, but in more complex projects, you want to use constants to quickly change certain (fixed) values without checking every line.

Getter and Setter methods are used in Object-oriented programming to keep variables encapsulated and provide an interface to make those variable accessable by other classes

北凤男飞 2024-10-05 08:15:56

问:为什么要使用 getter 和 setter?

答:将它们与私有实例变量结合使用可以让您准确定义如何更改字段的值。这可能会变得乏味,因为大多数时候,getter 和 setter 只会获取/设置值,而没有任何检查或副作用。但即使在代码中,您也可以看到 FaceValue 的设置器如何检查给定的值是否在 0 和 MAX 之间。这保证了当任何人(包括您自己)想要更改 FaceValue 时,都会检查输入。

这称为封装,您可以对类外部的所有内容隐藏类的字段,并定义如何更改获取和操作这些字段的非常具体的方法。

问:为什么将faceValue设置为1?

答:这只是将faceValue初始化为1。所以如果你在没有先掷骰子的情况下调用getValue,它总是返回1。它可以是你想要的任何值。

问:为什么要使用MAX?

答:在代码中使用常量作为任何常量是非常好的编程习惯。

首先,它使代码更易于阅读。如果我在阅读您的代码时看到 value <= 6,我会对 6 实际是什么感到困惑。如果我看到类似 DICE_MAX_VALUE 的内容,那么我就确切地知道您在检查什么。

其次,也许更重要的是,使用常量可以让您定义一次并在任何地方使用它,并保证具有相同的值。如果您想将其更改为 20 面骰子,则必须进入代码并将所有“6”实例更改为“20”,这可能很烦人、耗时且容易出错。

Q: Why use getters and setters?

A: Using them in conjuction with private instance variables allows you to define exactly how the value of a field is to be changed. It might become tedious because most of the time, getters and setters will just get/set the value without any checks or side effects. But even here in your code, you see how the setter of faceValue checks to see if the value given is between 0 and the MAX. This guarentees when anyone, including yourself, wants to change faceValue, the input will be checked.

This is called encapsulation, where you hide the fields of a class from everything outside that class and define very specific ways on how to change get and manipulate those fields.

Q: Why set faceValue to 1?

A: This just initializes faceValue to 1. So if you call getValue without first rolling the die, it will always return 1. It can be anything you want.

Q: Why use MAX?

A: It is very good programming practice to use constants for any constant in your code.

First of all, it makes the code easier to read. If I were reading your code and I saw value <= 6, I'd be confused about what 6 actually is. If I saw something like DICE_MAX_VALUE, then I know exactly what you were checking.

Secondly, perhaps more importantly, using constants lets you define it once and use it anywhere and be guarenteed to have the same value. If you ever wanted to change this into a 20 faced die, you'd have to go into your code and change all instances of '6' into '20' and that can be annoying, time consuming, and error prone.

谜兔 2024-10-05 08:15:56

设置faceValue是在初始化时分配合理的骰子滚动,而不依赖于对roll()的调用。使用 MAX 而不是 6 可以更轻松地更改骰子尺寸 - 例如,许多其他游戏使用不同的骰子尺寸,也许您想将此代码移植到它们中。

附带说明一下,问题代码中的格式需要做一些工作来提高可读性。

Setting faceValue is assigning a reasonable die roll upon initialization, without depending on a call to roll(). Using MAX instead of 6 makes it easier to change the die size - e.g., plenty of other games use different die sizes and maybe you want to port this code to them.

As a side note, the formatting in the question code could use a little work to improve readability.

公布 2024-10-05 08:15:56

这就是我们所说的数据类,这意味着该类用于表示在程序中发送的数据,在本例中是芯片的数据。
如果正确完成,Getters/Setter 允许您访问此数据并更改值,创建这样的数据类在创建多个数据类时非常有用,因此在您的情况下,如果您只是在主类中声明这些变量,那么这将是非常困难和尴尬的尽管您可以创建多个骰子实例,但以这种方式创建了多个骰子。
至于面值为 1,我认为这是因为真实骰子的值永远不会为 0,因此设置为 1 是掷骰子之前的默认值。它实际上可以是任何值,因为它们都有相似的概率。
您使用 max 是因为它始终为 6,这样就不会被任何其他方法错误地更改。
希望有帮助
+1 对于初学者来说好问题
谢谢克里斯

So this is what we call a Data class this means that this class is used to represent the data that's getting sent around your program in this case its the data for the die.
The Getters/Setters if done correctly allow you to access this data and change values , creating data classes like this is useful when creating multiples, so in your case if you just declared these variable within the main class it would be very hard and akward to created multiple dies this way though you can create multiple instances of die.
As far as facevalue being 1 i assume this is because the value of a real die is never 0 so therefore setting to one is the default value before the roll. it could be any value really as they all have similar probabilitys.
You use max because its always going to be 6 and this way it cannot be changed by any other methods by mistake.
Hope that helps
+1 Good Question for Beginners
Thanks Chris

情泪▽动烟 2024-10-05 08:15:56

简单地

//为什么要设置faceValue为1?

因为默认值设置为 0 。这在您的逻辑中是不可取的。

//为什么我们使用MAX而不是仅仅使用
6号?

使用常量值作为公共静态最终字段总是更好的做法

Simply

//why do you set the faceValue as 1?

because default value set would be 0 .it is not desirable in your logic so one.

//Why do we use MAX instead of just
number 6?

Its always better practice to use constant values as public static final field

守望孤独 2024-10-05 08:15:56
//why do you set the faceValue as 1?

在Java中,整数默认设置为0,但在骰子中没有面具有0值。

//Why do we use MAX instead of just number 6?

使用了 MAX,这样每当你想要更新 MAX 的值时,你就在一处更新它。无论您在哪里使用过它,它都会得到更新。通过这种方式,维护和适应变化变得容易。

//why do you set the faceValue as 1?

In Java, integers are set to 0 by default, but in dice there is no face has 0 value.

//Why do we use MAX instead of just number 6?

MAX is used, so that whenever you want to update the value of MAX, you update it at one place. And it will get updated where ever you have used it. In this way it becomes easy to maintain and accommodate changes.

伊面 2024-10-05 08:15:56

这个例子直接出自我大学时使用的一本教科书。您参加了瑞尔森大学的 ITM 项目吗?

请记住,物理骰子会掷出 1 到 6 之间的任何数字。请考虑以下事项:

public class Monopoly
{
  public static void main(String[] args)
  {
     Die myDie = new Die();
     System.out.println(myDie.getFaceValue());
  }
}

如果您的构造函数没有初始化面值,您认为会发生什么?

使用 MAX 而不是 6 更多地与代码可读性有关。在一个大程序中,你可以在任何地方放置 6。这对你来说很好,因为它是你写的,但是两年后取代你的开发人员会到处看到这些 6,并且可能不明白你为什么使用数字 6。通过使用常数 (MAX) 并使用这个词,您正在为正在发生的事情添加更多背景信息。其次,如果游戏规则更改为使用从 1 到 8 的骰子,则在一个区域中更新 MAX = 8 会更容易,而不是在各处将 6 更改为 8。

This example is directly out of a textbook I used in university. Are you in Ryerson's ITM program?

Remember that a physical die will roll anything between a 1 and a 6. Consider the following:

public class Monopoly
{
  public static void main(String[] args)
  {
     Die myDie = new Die();
     System.out.println(myDie.getFaceValue());
  }
}

What do you think would happen if your constructor did not initialize facevalue?

Using MAX instead of 6 has more to do with code readability. In a big program, you could put 6 everywhere. It would be fine for you because you wrote it, but the developer that comes to replace you in two years would see these 6s everywhere and may not understand why you used the number 6. By using a constant (MAX) and using that word, you're adding more context to what's going on. Secondly, if the game rules change to use a die that goes from 1-8, it's easier to update MAX = 8 in one area, as opposed to changing 6s to 8s everywhere.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文