我想我需要做一些类型转换才能让粉丝输出toString
,
为我的速度而不是1,2和3输出字符串。我不知道在哪里可以进行这些更改,要么在测试类中发送,要么在粉丝类中移动到私有。我试图在toString中添加一些调用,但我得到十六进制十进制结果。解决这个问题的一些不同方法非常有用。
public class Fan {
public final int SLOW = 1;
public final int MEDIUM = 2;
public final int FAST = 3;
private int speed; // = SLOW;
private boolean on; // on = false;
private double radius; // radius = 5;
private String color; // = "white";
public int getSpeed ( ) {return speed; }
public void setSpeed ( int speed ) { this.speed = speed; }
public boolean isOn ( ) {return on; }
public void setOn ( boolean on) {this.on = on; }
public double getRadius ( ) {return radius; }
public void setRadius ( double radius ) { this.radius = radius; }
public String getColor ( ) { return color; }
public void setColor ( String color ) { this.color = color; }
public Fan ( ) {
System.out.println("Default constructor called");
}
// default constructor
public Fan ( int speed, boolean on, double radius, String color ) {
this.speed = speed;
this.on = on;
this.radius = radius;
this.color = color;
System.out.println("Overloaded constructor called");
}
//overloaded constructor
public String toString () {
String x = "speed is " + speed + ", is the fan turned on? " + on + ",the radius "
+ "of the blades are " + radius + ", and the color of the fan is " + color;
return x;
}
}
public class FanTest {
public static void main(String[] args) {
Fan f1 = new Fan( 3, true, 10, "Yellow" ) ;
Fan f2 = new Fan();
Fan f4 = new Fan();
f1.equals(f4) ;
Fan f3 = f1;
int slow = 1;
int medium = 2;
int fast = 3;
System.out.println(f1);
System.out.println(f2);
System.out.println(f3);
if (f1.equals(f3)) {
System.out.println("Obejects r3 and r1 are the same\n");
} else {
System.out.println("Objects r3 and r1 are different");
}
while (f1.equals(f4))
f4.setOn(false);
f4.setSpeed(2);
f4.setColor("green");
f4.setRadius(8);
System.out.println(f4);
}
}
答案 0 :(得分:0)
首先,在默认构造函数中没有设置变量。这意味着使用默认构造函数创建的任何Fan对象都处于无效状态(例如,speed
默认为0
)。我建议你取消注释第9-12行:
private int speed = SLOW;
private boolean on = false;
private double radius = 5;
private String color = "white";
你说你想要为我的速度而不是1,2和3"输出字符串。这可以使用if..else
或switch
轻松实现。
if (speed == 1) {
str = str + " slow ";
} else if (speed == 2) {
str = str + " medium ";
} else if (speed == 3) {
str = str + " fast ";
}
使用开关:
switch (speed) {
case 1:
str = str + " slow ";
break;
case 2:
str = str + " medium ";
break;
case 3:
str = str + " fast ";
break;
}
关于f1.equals(f4)
:这些是不同的对象,因此永远不会true
。
关于equals
:equals
是类Object
中定义的方法,因此可以在任何对象上使用。但除非你覆盖它,否则会检查身份,这意味着
a.equals(b)
始终返回与
相同的内容a == b