【问题标题】:create and compare child classes创建和比较子类
【发布时间】:2015-11-03 17:33:17
【问题描述】:

大家好,抱歉,如果这是一个常见且烦人的问题,我正在尝试创建一个父类(用于 3 个单独的类),但我真的不确定从这里去哪里。

我需要它们在 0

或者我不需要 3 个新课程,而是我可以在同一个课程中全部完成?

如果您认为我需要它,请随时添加建议。

TIA

public class Soldier {
    public static void main(String args[]) {

            Random random = new Random();
            double max = 100; //sets the limit to 100 for the soldiers spawn
            double min = 0; //sets the minimum to 0 for the soldiers spawn
            double xPos = Math.random() * (max - min) - min;//for the x coordinate of the soldiers position
            double yPos = Math.random() * (max - min) - min; //for the y coordinate of the soldiers position
            xPos = Math.round(xPos * 10) / 10.0d; //making sure the x value is to 1dp
            yPos = Math.round(yPos * 10) / 10.0d; //making sure the y value is to 1dp
            System.out.println("(" + xPos + " ," + yPos + ")"); //printing out the position of the soldier (x, y)

        }

    }

【问题讨论】:

  • 您的问题似乎至少包含 3 个问题,其中 0 个问题表达清楚足以给您一个正确的答案。您要解决的实际问题是什么?是什么让您想到了子班?

标签: java inheritance parent-child


【解决方案1】:

我不确定父子是否与它有关,但这是我认为您想要的:

public static void main(String ... args){
  double min = 0;
  double max = 100;

  Point p1 = generatePoint(min, max);
  Point p2 = generatePoint(min, max);
  Point p3 = generatePoint(min, max);
}

public static Point generatePoint(double min, double max){
  double xPos = Math.random() * (max - min) - min;
  double yPos = Math.random() * (max - min) - min; 

  return new Point((int) xPos, (int) yPos);
}

【讨论】:

  • 感谢您的帮助,最后一件事,我怎样才能使这个 double 而不是 int? return new Point((int) xPos, (int) yPos);
【解决方案2】:

我认为您不需要 3 个类,只需要 3 个此类对象的实例。我会在类中添加一个“id”成员,以便您可以区分它们。我还会添加几个类范围的 static 成员,一个用于跟踪我们在实例化更多士兵时所使用的“id”,也许还有一个指向这些实例的指针数组,以使其更容易查找和操作实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多