-1

I have to create a program which has a list of houses. In this houses there has to be this information: direction, zipcode, number of rooms and the square meters of the house. One of my biggest problems is that this information has to be segmented. So, first the list of directions have to be shown, then the list of zipcodes, then the number of rooms...

I created a class House and I set the String variables for each one (direction, zipcode, number of rooms and the square meters of the house).

I know that I should be using arrays, for and objects but It's my first assignment and I am really lost on how or where should I start.

I really want to learn how to do it, so if you have any idea, tip or suggestion I would appreciate it. I don't want people to do my assignment I just want to know how can I get started. thank you!

This is my code so far:

package ejerciciofinalt3;

public class HouseExercise {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        House house1 = new House();
        house1.showHouseInfo();

        house1.direction = "abc";
        house1.postCode = "08397";
        house1.roomNumber = "4";
        house1.squareMeter = "100";


        house1.showHouseInfo();

    }

}
Pradip Tilala
  • 1,715
  • 16
  • 24
  • [Take a look at how to override `toString()`](https://stackoverflow.com/questions/10734106/how-to-override-tostring-properly-in-java) – Aniket Sahrawat Oct 03 '19 at 11:03

3 Answers3

0

Initialize a String Array like this:

String[] housePropertiesArray = new String[]{"abc", "08397", "4", "100"};

...in the House class. Then you could write a method to return all of them:

public String getProperties(){
String output = "";
for(String property : housePropertiesArray){
output += property + "\n";
}
return output;
}

In the outputString you would have a superfluous \n in the end, just a newLine-Tag but wouldnt matter much I hope.

pikkuez
  • 310
  • 1
  • 18
0

Create an ArrayList and add each house in that List. Then for each of the segments (directions, zipCodes, etc) do a for loop and print the segment:

 List <House> houseL = new ArrayList();
 houseL.add(house1);
 houseL.add(house2);
 houseL.add(house3);
 System.out.println("-- Directions --");
 for (House house:houseL){
    System.out.println(house.getDirection());
 }
 System.out.println("-- Zip Codes--");
 for (House house:houseL){
    System.out.println(house.getPostCode());
 }
//etc

You should have getters in House class.

Ioannis Barakos
  • 1,319
  • 1
  • 11
  • 16
0

Try to override the toString() method like

class House{
...
@override
public String toString(){
  return String.format("direction: %s postCode: %s roomNumber: %s squareMeter : %s", 
  this.direction, this.postCode, this.roomNumber, this.squareMeter);  
}

after if you want to display just call

System.out.println(house.toString());

Or

System.out.println(house);
heyhooo
  • 82
  • 6