本文介绍了Java控制台显示对象地址而不是实际值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,所以我有一个用Java处理的简单数组.问题是,当我运行程序时,我得到的是对象的地址而不是实际值.我也看到循环/数组有问题.它应该显示3、5和7号房屋,但底部显示3,4和5号房屋.请参见下面的代码和控制台输出.预先感谢!

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]);
}

控制台输出:

3号房中的瓶子数量是:org.com1027.lab3.House@d16e5d6

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

5号门的瓶子数是:org.com1027.lab3.House@5a4b4b50

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

7号房中的瓶子数量是:org.com1027.lab3.House@53d9f80

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

3号屋中的瓶子数是org.com1027.lab3.House@d16e5d6

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

第4个房子中的瓶子数是org.com1027.lab3.House@5a4b4b50

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

第5个房子中的瓶子数是org.com1027.lab3.House@53d9f80

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

推荐答案

Java没有任何机制可以神奇地知道您的类应如何以字符串格式表示.这就是为什么您必须自己实现它.

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.

您需要重写toString()方法以获取正确"值

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

class House {
 //your code

 @Override 
 public String toString() {
   return "The string representation";
 }

}

这篇关于Java控制台显示对象地址而不是实际值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 23:28