toString()方法不能打印正确的对象值

时间:2015-08-06 20:13:50

标签: java

我正在关注一本书,我有一个Point类,它定义了一个点,我试图显示这些值。我一直在寻找一段时间,无论我做什么,总是显示[0,0]这是我的代码。

  class Main {

    public static void main(String []args) {
        Point point = new Point(10, 20);
        System.out.println(point.toString());
    }      
  }

  class Point {

    private int x, y;

    public Point(int x, int y) {
      x = x;
      y = y;
    }

    public String toString() {
      return "[" + x + ", " + y + "]";
    }

5 个答案:

答案 0 :(得分:6)

您实际上从不初始化班级成员<ion-list> <ion-item class="item-text-wrap item-thumbnail-right"> <img ng-src="{{category.photo}}" /> <h2>Name</h2> <p>{{description}}</p> </ion-item> <ion-item class="item-text-wrap item-thumbnail-right"> <img ng-src="{{category.photo}}" /> <h2>Name</h2> <p>{{description}}</p> </ion-item> </ion-list> class SomeCaseClass(val string:String) {} val a = "123" assertTrue( a.equals( a ) ) // Passes assertTrue( new SomeCaseClass(a).equals( new SomeCaseClass(a) ) ) // Fails, Scala 2.10 。因此,它们会自动初始化为0,因此x输出。

y表示参数x =参数x,它什么都不做。

使用[0,0]代替x = x类成员this.x = x;

答案 1 :(得分:2)

在构造函数中使用它,如下所示: -

class Point {

private int x, y; // These x and y are member of Point class

public Point(int x, int y) {
  this.x = x;
  this.y = y;
}

public String toString() {
  return "[" + x + ", " + y + "]";
 }

您没有初始化Point类的x和y。 在toString()方法中,您打印的Point类的x和y未初始化,因此默认值为0,即0是整数的默认值。

答案 2 :(得分:2)

看看你的构造函数:

$http({
    url:'api/?r=page/product',
    method:'post',
    params:{
       price:$scope.price
    },
});

在您的情况下,您不初始化类字段。为此,请使用$.ajax({ url:'api/?r=page/product', method:'post', data:{ price:$scope.price } }); 关键字,它应如下所示:

public Point(int x, int y) {
      x = x;
      y = y;
    }

否则,您只处理参数thispublic Point(int x, int y) { this.x = x; this.y = y; } 变量。

答案 3 :(得分:1)

使用this关键字分隔局部变量和实例变量。在参数化构造函数中,jvm无法初始化实例变量,因为它在本地变量和实例变量之间出现歧义问题。如果我们没有初始化那么你可以隐式初始化java中的实例变量,这就是你输出[0,0]的原因。

这是代码..

class Main {

public static void main(String []args) {
    Point point = new Point(10, 20);
    System.out.println(point.toString());
}      

}

class Point {

private int x, y;

public Point(int x, int y) {
  this.x = x;
  this.y = y;
}

public String toString() {
  return "[" + x + ", " + y + "]";
}

答案 4 :(得分:0)

Constructor Point对象的 public Point(int x, int y) { this.x = x; this.y = y; }

this.x

您需要设置Point表示您正在设置x对象的x变量的值,而不是传递给 class Main { public static void main(String []args) { Point point = new Point(10, 20); System.out.println(point.toString()); } } class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public String toString() { return "[" + x + ", " + y + "]"; } 的{​​{1}}参数构造

更新的功能代码如下:

  var index = clients.indexOf(connection);
  clients.splice(index, 1);
  room.splice(index, 1);
相关问题