设计一个名为MyPoint的不可变类,它代表一个坐标为x,y的点(x和y不能为负数)。类包含: 私有成员变量x和y代表坐标,类型为double。 一个不带参数的构造方法MyPoint(),x和y都设为0.0。 一个有参构造方法MyPoint(doub
时间: 2023-06-06 07:04:52 浏览: 64
le x, double y), 参数分别为x和y。 如果输入的参数有负数,则抛出IllegalArgumentException异常,提示用户输入的x和y必须为正数。
以下是MyPoint类的代码实现:
```
public class MyPoint {
private double x;
private double y;
public MyPoint() {
this.x = 0.0;
this.y = 0.0;
}
public MyPoint(double x, double y) {
if (x < 0 || y < 0) {
throw new IllegalArgumentException("x和y必须为正数");
}
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public String toString() {
return "(" + x + ", " + y + ")";
}
}
```
以上是代码的实现,您可以将其复制并粘贴到您的开发环境中。如果您发现任何问题或有任何疑问,请告诉我。
相关问题
设计一个MyPoint类,表示具有x坐标和y坐标的点
class MyPoint:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "Point(" + str(self.x) + ", " + str(self.y) + ")"
def distance(self, other_point):
return ((self.x - other_point.x) ** 2 + (self.y - other_point.y) ** 2) ** 0.5
def move(self, dx, dy):
self.x += dx
self.y += dy
设计一个名为MyPoint的不可变类,它代表一个坐标为x,y的点(x和y不能为负数)。类包含: 私有成员变量x和y代表坐标,类型为double。 一个不带参数的构造方法MyPoint(),x和y都设为0.0。 一个有参构造方法MyPoint(double x,double y),构造一个指定的坐标点,如果x和y小于0,则设为0。 为x和y添加getter方法,都为公共方法。 public MyPoint move(double dx, double dy)方法, 生成一个横坐标移动dx,纵坐标移动dy后的
新点,并返回该新点,但原始点不变。
以下是设计的代码:
```java
public final class MyPoint {
private final double x;
private final double y;
public MyPoint() {
this.x = 0.0;
this.y = 0.0;
}
public MyPoint(double x, double y) {
if (x < 0) {
this.x = 0.0;
} else {
this.x = x;
}
if (y < 0) {
this.y = 0.0;
} else {
this.y = y;
}
}
public double getX() {
return this.x;
}
public double getY() {
return this.y;
}
public MyPoint move(double dx, double dy) {
return new MyPoint(this.x + dx, this.y + dy);
}
}
```
希望这个代码可以满足您的需求!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)