英文:
Trouble with testing IllegalArgumentException
问题
我在通过我的IllegalArgumentException测试时遇到了问题。当没有对象传递给我的方法时,IllegalArgumentException将不会发生。
public double distanceTo(Point otherPoint) {
int x = (otherPoint.x - this.x);
int y = (otherPoint.y - this.y);
double xDbl = Math.pow(x, 2);
double yDbl = Math.pow(y, 2);
if (otherPoint!=null) {
return Math.hypot(xDbl, yDbl);
} else {
throw new IllegalArgumentException("未提供otherPoint对象的值");
}
}
英文:
I am having trouble with passing tests for my IllegalArgumentException. When no object is passed into my method, the IllegalArgumentException will not happen.
public double distanceTo(Point otherPoint) {
int x = (otherPoint.x - this.x);
int y = (otherPoint.y - this.y);
double xDbl = Math.pow(x, 2);
double yDbl = Math.pow(y, 2);
if (otherPoint!=null) {
return Math.hypot(xDbl,yDbl);
} else {
throw new IllegalArgumentException("No value for otherPoint object");
}
}
答案1
得分: 1
代码部分不需要翻译,这里是翻译后的内容:
由于在函数开始时访问了otherPoint
的属性x
和y
,如果otherPoint
为null,它将抛出NullPointerException而不是IllegalArgumentException。为了在otherPoint
为null时抛出IllegalArgumentException,您需要将null检查放在函数的开头,即在访问属性x
和y
之前。
public double distanceTo(Point otherPoint) {
if (otherPoint == null) {
throw new IllegalArgumentException("没有提供otherPoint对象");
}
int x = (otherPoint.x - this.x);
int y = (otherPoint.y - this.y);
double xDbl = Math.pow(x, 2);
double yDbl = Math.pow(y, 2);
return Math.hypot(xDbl, yDbl);
}
英文:
Since you're accessing properties x
, y
of otherPoint
at the beginning of the function, if otherPoint
is null, it will throw the NullPointerException instead of IllegalArgumentException. In order to throw the IllegalArgumentException when otherPoint
is null
, you need to bring your null check in the if statement to the beginning of the function, before accessing the properties x
and y
public double distanceTo(Point otherPoint) {
if (otherPoint==null) {
throw new IllegalArgumentException("No value for otherPoint object");
}
int x = (otherPoint.x - this.x);
int y = (otherPoint.y - this.y);
double xDbl = Math.pow(x, 2);
double yDbl = Math.pow(y, 2);
return Math.hypot(xDbl,yDbl);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论