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";
}
}