0

我的代码打印 0 而不是大小和年份。我究竟做错了什么?基本上我希望它返回那些,但我不确定我在做什么。

public class House {
private int year;
private int size;
private static int nbrOfHouses; 
public static final int MIN_SIZE =10; 

public House(int _year,int _size){
    _year = year;
    _size = size;
}
public static int getNbrHouses(){ 
    return nbrOfHouses;
}
public int getYear(){
    return year;
    }
public int getSize(){
    return size;
}
}


House[] myHouse = new House[10];{
  myHouse[0] = new House(1902, 120);
  myHouse[1] = new House(1954, 180);
  myHouse[2] = new House(1995,90);

  for(int i=0; i< myHouse.length; i++){
        if(myHouse[i]!=null){
          System.out.println(myHouse[i].getYear());
4

5 回答 5

5

这是倒退:

public House(int _year,int _size){
    _year = year;
    _size = size;
}

应该:

public House(int _year,int _size){
    year = _year;
    size = _size;
}

或者更好:

public House(int year,int size){
    this.year = year;
    this.size = size;
}
于 2013-09-02T04:55:03.903 回答
4

在您的构造函数中,您没有正确分配类变量。做这个:

public House(int _year,int _size){
    year = _year;
    size = _size;
}

您已将参数分配给类变量(初始化为 0)。由于类变量被初始化为 0 并且没有被修改,这就是它打印 0 的原因。

正如@pfrank 所提到的,Java 命名约定通常没有下划线。一种更传统的编码方式是使用this关键字。

public House(int year,int size){
    this.year = year;
    this.size = size;
}
于 2013-09-02T04:53:06.317 回答
2

采用

public House(int _year,int _size){

this.year = _year;
this.size = _size;
}
于 2013-09-02T04:54:10.087 回答
1

字段未正确初始化。

public House(int _year,int _size){
    this.year = _year;
    this.size = _size;
}
于 2013-09-02T04:53:33.977 回答
1

Java 语言规范第 15.26 节指出

AssignmentExpression:
    ConditionalExpression
    Assignment

Assignment:
    LeftHandSide AssignmentOperator AssignmentExpression

LeftHandSide:
    ExpressionName
    FieldAccess
    ArrayAccess

AssignmentOperator: one of
    = *= /= %= += -= <<= >>= >>>= &= ^= |=

您总是从右侧分配到左侧。这

public House(int _year,int _size){
    _year = year;
    _size = size;
}

因此是相反的,应该是

year = _year;
size = _size;

此外,由于原始类型的实例字段默认初始化为 0,因此所有int字段的值都为 0。

于 2013-09-02T04:53:50.433 回答