【问题标题】:How do I add the return statement?如何添加return语句?
【发布时间】:2019-09-04 13:13:07
【问题描述】:

Java

我想在我的其他班级访问“dist”。但是我不能这样做,因为变量在方法中。我无法将方法更改为“public double”,因此我无法将其放入 get 方法中。提示?

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    for (Circle circle : circles) {
        circle.draw(g);
        if (selectedCircle != null && selectedCircle == circle) {
            selectedCircle.drawSelected(g);
        }
    }

    for (int i = 0; i < circles.size(); i++) {
        Circle c1 = circles.get(i);
        for (int j = i + 1; j < circles.size(); j++) {
            Circle c2 = circles.get(j);

            double dist = c1.getPoint().distance(c2.getPoint()) + 1;
            double dx = (c2.x - c1.x) / dist / dist;
            double dy = (c2.y - c1.y) / dist / dist;
            c1.x += dx;
            c1.y += dy;
            c2.x -= dx;
            c2.y -= dy;

        }
    }

}

【问题讨论】:

  • 请不要添加代码图像,将文本添加到您的问题中。还用语言标记您的问题
  • 如果您需要所有可能的circles 对之间的距离,您可以将它们存储在List&lt;Double&gt;double[] 中,并使用i, j 来确定索引,以获得平坦的数据结构和避免使用 Map&lt;Pair&lt;Circle, Circle&gt;, Double&gt; 之类的东西。
  • @EdgarAsatryan 我的目标是在我的 Circles 类中简单地使用“dist”。在那里我添加了一个 if 语句: if(dist

标签: java variables methods return


【解决方案1】:

如果您的圈子发生了某种变化,paintComponent 方法将更新您的圈子。它不是自己进行这些更改的地方。因此,第二个循环中的代码应该移到别处,例如,移到Circle 的构造函数和/或moveCircle 方法中。进行这些更改后,系统将调用paintComponent。另外,关于第一个循环,不清楚selectedCircle 是什么,可能是一个实例变量。如果是这样,请不要在循环内绘制它,而只能绘制一次。

【讨论】:

  • 谢谢,这是一些有用的提示!
【解决方案2】:

您可以将dist 声明移到您的方法之外并进入类主体,然后为您的其他类提供一个getter 以利用它来访问它。

private double dist;

public double getDist() {
   return dist;
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    for (Circle circle : circles) {
        circle.draw(g);
        if (selectedCircle != null && selectedCircle == circle) {
            selectedCircle.drawSelected(g);
        }
    }

    for (int i = 0; i < circles.size(); i++) {
        Circle c1 = circles.get(i);
        for (int j = i + 1; j < circles.size(); j++) {
            Circle c2 = circles.get(j);

            dist = c1.getPoint().distance(c2.getPoint()) + 1;
            double dx = (c2.x - c1.x) / dist / dist;
            double dy = (c2.y - c1.y) / dist / dist;
            c1.x += dx;
            c1.y += dy;
            c2.x -= dx;
            c2.y -= dy;

        }
    }

}

【讨论】:

    猜你喜欢
    • 2014-12-02
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 2022-08-08
    • 1970-01-01
    • 2016-12-29
    • 2017-02-05
    • 2016-01-29
    相关资源
    最近更新 更多