java怎么获取控制台对象,Java控制台显示对象地址而不是实际值

Ok so I've got a simple array that I'm working on in Java. Problem is, when I run the program I get the address of the object rather than the actual value. I also see to have a a problem with the loop/array. It should display houses 3, 5 and 7 but the bottom part is showing 3,4 and 5. Where am I going wrong? Please see code below, and console output. Thanks in advance!

House[] houses = new House[3];

houses[0] = new House(3,4);

houses[1] = new House(5,7);

houses[2] = new House(7,2);

System.out.println("Number of bottles in house number 3 is: " + houses[0]);

System.out.println("Number of bottles in house number 5 is: " + houses[1]);

System.out.println("Number of bottles in house number 7 is: " + houses[2]);

for (int i = 0; i < houses.length; i++){

System.out.println("Number of bottles in house " + (i + 3 ) + " is " + houses[i]);

}

Console Output:

Number of bottles in house number 3 is: org.com1027.lab3.House@d16e5d6

Number of bottles in house number 5 is: org.com1027.lab3.House@5a4b4b50

Number of bottles in house number 7 is: org.com1027.lab3.House@53d9f80

Number of bottles in house 3 is org.com1027.lab3.House@d16e5d6

Number of bottles in house 4 is org.com1027.lab3.House@5a4b4b50

Number of bottles in house 5 is org.com1027.lab3.House@53d9f80

解决方案

Java do not have any mechanism that magically know how your class should be represented in string format. That is why you must implement it by your own.

You need to override the toString() method to gain "corect" value

class House {

//your code

@Override

public String toString() {

return "The string representation";

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值