gpt4 book ai didi

Java 矩形和转换

转载 作者:行者123 更新时间:2023-11-29 03:52:22 25 4
gpt4 key购买 nike

显然,根据类作业,这是家庭作业..所以尽可能多地帮助我,不要因为我发布硬件而责备我,好吗?

在过去的两个小时里,我已经快要死了,通读了我的书,在线通读了,但天哪,我找不到为什么这个愚蠢的矩形显示“找不到方法 setX()”。还有没有办法使 double 成为整数而不将它们转换为整数?它看起来真的很乱,我们不应该添加任何东西,除了在封闭的方法中......我想我必须投??

感谢您提供的任何帮助..

import java.awt.Rectangle;
import java.util.ArrayList;

public class Homework18A
{
public static void main(String[] args)
{
ArrayList<Rectangle> test = new ArrayList<Rectangle>();
test.add(new Rectangle(10, 20, 30, 40));
test.add(new Rectangle(20, 10, 30, 40));
test.add(new Rectangle(10, 20, 40, 50));
test.add(new Rectangle(20, 10, 50, 30));
Rectangle enc = enclosing(test);
System.out.println(enc);
System.out.println("Expected: java.awt.Rectangle[x=10,y=10,width=60,height=60]");
}

/**
Computes the smallest rectangle enclosing all rectangles in
an array list.
@param rects an array list of rectangles of size >= 1
@return the smallest rectangle enclosing all rectangles in rect
*/
public static Rectangle enclosing(ArrayList<Rectangle> rects)
{
Rectangle containRec = new Rectangle(0, 0, 0, 0);
for(int i = 0; i < rects.size(); i++) {
if(rects.get(i).getX() < containRec.getX())
containRec.setX((int)rects.get(i).getX());
if(rects.get(i).getY() < containRec.getY())
containRec.setY((int)rects.get(i).getY());
if(rects.get(i).getX() + rects.get(i).getWidth() > containRec.getWidth())
containRec.setWidth(((int)rects.get(i).getX() + rects.get(i).getWidth()));
if(rects.get(i).getY() + rects.get(i).getHeight() > containRec.getHeight())
containRec.setHeight(((int)rects.get(i).getY() + rects.get(i).getHeight()));
}
return containRec;
}
}

最佳答案

因为 Rectangle 没有方法 setX()setY()。如果您尝试设置要使用的位置,请使用 setLocation(x,y)

编辑:也没有 setWidth() 或 setHeight() 方法,您想使用 setSize(width, height)。尽管 Rectangle 类具有 x、y、宽度和高度的字段,但它不遵循常规的 Java 约定,在该约定中,字段设为私有(private)并使用公共(public) getter 和 setter 方法。在这种情况下,您可以直接访问这些字段,只需说 containRec.x = whatever,但这是一个坏习惯。

您不想删除 (int) 强制转换,但您绝对可以清理该部分。除了调用 rects.get(i),您还可以在循环的开头放一行 Rectangle currentRect = rects.get(i); 或者更好的方法是使用 for-each 循环。

关于Java 矩形和转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8147711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com