我正在尝试发起一个对象"有理数"存储分子p
,分母q
及其比率r
。此代码产生错误的答案。
class Rational {
int p, q;
double ratio;
public Rational(){
this.p = 0;
this.q = 1;
this.ratio = this.p/(double)(this.q);
}
public static void main (String[]arg) {
Rational r1 = new Rational();
r1.p = 1;
r1.q = 7;
// r1.ratio = r1.p/(double)(r1.q); //"this line"
System.out.println (r1.p + "/" + r1.q + " = " + r1.ratio) ;
}
}
取消注释"此行"解决了这个问题。如何定义对象,以便每次更改this.r
或this.p
时this.q
都会自动更新?
答案 0 :(得分:4)
在我看来,更简单的方法是定义一个名为ratio的函数,而不是变量。
class Rational {
private int p, q;
public Rational(){
this.p = 0;
this.q = 1;
}
public double ratio(){
return (double)p/(double)q;
}
//define the getters and setters for p and q
}
然后,只要你想要比率,你应该调用方法: myRational.ratio()
答案 1 :(得分:3)
在大多数情况下,最好的选择是使类Rational不可变,这样您就不必处理不一致的状态,并且在状态发生变化时不需要添加逻辑来更新派生字段。也就是说,你想要另一个Rational吗?只是构建它。期。它看起来像这样:
class Rational {
final int p;
final int q;
final double ratio;
public Rational(int p, int q){
this.p = p;
this.q = q;
this.ratio = this.p/(double)(this.q);
}
public static void main (String[]arg) {
Rational r1 = new Rational(1, 7);
System.out.println (r1.p + "/" + r1.q + " = " + r1.ratio) ;
}
}
Bonus,您可以将字段设为私有字段并使用getter公开它们,以获得更加封装的设计。
答案 2 :(得分:2)
通过将此构造函数添加到Rational类:
public Rational(int p, int q){
this.p = p;
this.q = q;
this.ratio = this.p/(double)(this.q);
}
答案 3 :(得分:2)
class Rational {
int p;
int q;
double ratio;
public Rational(){
this.p = 0;
this.q = 1;
this.ratio = this.p/(double)(this.q);
}
public void setP(int p) {
this.p = p;
this.ratio = this.p/(double)(this.q);
}
public void setQ(int q) {
this.q = q;
this.ratio = this.p/(double)(this.q);
}
public static void main (String[]arg) {
Rational r1 = new Rational();
r1.setP(1);
r1.setQ(7);
System.out.println (r1.p + "/" + r1.q + " = " + r1.ratio) ;
}
}
答案 4 :(得分:1)
您应该添加一个更新它们的方法,例如
public void Update(int p, int q)
{
this.p = p;
this.q = q;
this.ratio = p/q;
}
您必须在现在更改p和q值的地方调用它并删除这两行。 这应该解决它:)
答案 5 :(得分:1)
在设置p和q后你没有更新你的比率变量,因此比率保持为0.你应该使用封装。
应该是这样的:
class Rational {
private int p, q;
private double ratio;
public Rational(){
this.p = 0;
this.q = 1;
updateRatio();
}
private updateRatio() {
ratio = p / (double)q;
}
public setQ(int q){
this.q =q;
updateRatio();
}
public getQ(){
return q;
}
//make getters and setters for variable p too
public getRatio(){
return ratio;
}
public static void main (String[]arg) {
Rational r1 = new Rational();
r1.setQ(1);
r1.setP(7);
System.out.println (r1.getQ() + "/" + r1.getP() + " = " + r1.getRatio()) ;
}
}