总是得到虚假阅读
尝试创建代码以验证三角形的原因,无论我输入什么,它都以false返回,
type public class Triangle {
private int side1;
private int side2;
private int side3;
private static int num_triangles=0;
private static int totalPerimeter=0;
/**
*
* @param side1
* @param side2
* @param side3
*/
public Triangle(int side1, int side2, int side3)
{
num_triangles++;
if (isValid() == true)
{
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
else if (isValid() == false)
{
this.side1 = 1;
this.side2 = 1;
this.side3 = 1;
}
totalPerimeter += calcPerim();
}
private boolean isValid()
{
return ((((side1)+(side2)) > (side3) && ((side1)+(side3)) > (side2) && ((side2) + (side3)) > (side1))) ;
}
我尝试将语句作为if语句返回前,我将其分为单个语句, 但是我会得到相同的结果
Trying to create code to validate a triangle for some reason, no matter what I input, it returns as false
type public class Triangle {
private int side1;
private int side2;
private int side3;
private static int num_triangles=0;
private static int totalPerimeter=0;
/**
*
* @param side1
* @param side2
* @param side3
*/
public Triangle(int side1, int side2, int side3)
{
num_triangles++;
if (isValid() == true)
{
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
else if (isValid() == false)
{
this.side1 = 1;
this.side2 = 1;
this.side3 = 1;
}
totalPerimeter += calcPerim();
}
private boolean isValid()
{
return ((((side1)+(side2)) > (side3) && ((side1)+(side3)) > (side2) && ((side2) + (side3)) > (side1))) ;
}
I tried putting the statement before return as an if statement, I separated it into individual statements,
but i would get the same result
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为当您调用
isValid()
时,您的属性尚未设置,因此this.side1
、this.side2
、this.side3当您调用
等于isValid()
时,0
。这也不是面向对象编程的使用方式。但是假设你只是想尝试 Java 的基础知识,如果你想让它工作,你的构造函数应该更像是:
That's because your attributes are not set when you call
isValid()
, hencethis.side1
,this.side2
,this.side3
are equals to0
when you callisValid()
.Also this is not how Oriented Object Programming is supposed to be used. But let say you just want to experiment the basics of Java, if you want to make it work, your constructor should be more like :