lundi 19 février 2018

if else in toString Java

For my class I was given a problem where I had to create a class called Fan. I was then told to assign different fields along with it, one of them being a boolean called on which if true meant the fan was on. At the end were told this

A method named toString() that returns a string description for the fan. If the fan is on, the method returns the fan speed, color, and radius in one combined string. If the fan is not on, the method returns the fan color and radius along with the string “fan is off” in one combined string. Write a Demo class that creates two Fan objects. Assign the following values for the first fan: speed: 1000rpm, radius: 12, color: blue, and fan-state: on. Assign the following values to the second fan: speed: 2000rpm, radius: 5, color: blue, and fan-state: off. Display the objects by invoking the toString method.

So I proceeded on and made the classes,

package p2;

public class Demo {

public static void main(String[] args) {
    Fan f1 = new Fan(1000, true, 12, "blue");
    Fan f2 = new Fan(2000, false, 5, "blue");
    // 1000rpm, radius: 12, color: blue, and fan-state: on
    //speed: 2000rpm, radius: 5, color: blue, and fan-state: off

    System.out.println(f1);
    System.out.println("----------------------------");
    System.out.println(f2);
}

}

package p2;

public class Fan {

private int speed;
private boolean on;
private double radius;
private String color;

public Fan()
{
    speed = 0;
    on = false;
    radius = 0;
    color = "none";
}

public Fan(int speed, boolean on, double radius, String color) {
    this.speed = speed;
    this.on = on;
    this.radius = radius;
    this.color = color;
}

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 String toString()
{
    if(on = true)
    {
        return "Fan Speed: " + getSpeed() + "rpm" + "\nFan Color: " + getColor() + "\nFan Radius: " + getRadius();
    }
    else
        return "*Fan is off*" + "\nFan Color: " + getColor() + "\nFan Radius: " + getRadius();
}

}

After running this I find that everytime I run it, regardless if one of my Fan objects is false, it will still return the true statement. Any help? Thanks!

Aucun commentaire:

Enregistrer un commentaire