java - 使用 toString 方法打印调整后的变量

标签 java tostring

我这里有一个非常基本的类,我正在尝试使用我的第一个 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/

相关文章:

java - Spring mvc : java. lang.AbstractMethodError

java - 如何在Project Reactor中正确使用Schedulers.single()?

perl - python/ruby的inspect方法中perl的repr等价物是什么

java - 打印 Java 数组的最简单方法是什么?

java - 二叉搜索树遍历方法,依次为toString

java - 如果类没有提供方法的实现,为什么类对象可以调用 toString 方法?

java - Android - 将图像附加到电子邮件

java - 推荐从 Jersey 开始的 Maven 原型(prototype)

java - 两种身份验证机制 : Kerberos and HTTP basic

c++ - 在 C++ 程序中使用 to_string 时出现编译错误