我这里有一个非常基本的类,我正在尝试使用我的第一个 toString() 方法。
public class Shoes
{
private String style;
private String color;
private double size;
public Shoes()
{
this.style = " ";
this.color = " ";
this.size = 0;
}
public Shoes(String newStyle, String newColor, double newSize)
{
this.style = newStyle;
this.color = newColor;
this.size = newSize;
System.out.println(this);
}
public String getStyle()
{
return style;
}
public void setStyle(String newStyle)
{
style = newStyle;
}
public String getColor()
{
return color;
}
public void setColor(String newColor)
{
color = newColor;
}
public double getSize()
{
return size;
}
public void setSize(double newSize)
{
size = newSize;
}
public String toString()
{
String myEol = System.getProperty("line.separator");
return new String("Style: " + style + myEol + "Color: " + color + myEol + "Size: " + size);
}
}
我试图拥有它,以便在我的主类中它会在变量数据发生变化时打印出来。现在我只知道如何在重载构造函数内调用它,但是在数据从其初始化值更改后如何打印它?
主类的示例,如您所见,我使用的是默认值并重载。
public class ShoeStore
{
public static void main(String[] args)
{
Shoes nerdShoes = new Shoes();
Shoes coolShoes = new Shoes("Sandals", "Brown", 8.5);
nerdShoes.setColor("Tan");
nerdShoes.setStyle("Walking");
nerdShoes.setSize(9.5);
System.out.println("The style of nerdShoes: " + nerdShoes.getStyle());
coolShoes.setColor("Purple");
System.out.println("The style of coolShoes: " + coolShoes.getStyle());
}
}
我做了什么来修复它
public String toString()
{
String myEol = System.getProperty("line.separator");
return new String("Style: " + getStyle() + myEol + "Color: " + getColor() + myEol + "Size: " + getSize());
}
我没有调用变量本身,而是调用了函数!我不知道我是怎么错过的。现在可以正常打印了!
最佳答案
只需添加
System.out.println(this);
在每个set
方法中。例如:
public void setStyle(String newStyle)
{
style = newStyle;
System.out.println(this);
}
关于java - 使用 toString 方法打印调整后的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36505880/