Java变量赋值

时间:2013-09-02 04:51:56

标签: java

我的代码打印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());

5 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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;
}

答案 2 :(得分:2)

使用

public House(int _year,int _size){

this.year = _year;
this.size = _size;
}

答案 3 :(得分:1)

字段未正确初始化。

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

答案 4 :(得分:1)

Java Language Specification section 15.26 states

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.