-1

I implement a adresbook and a adress class! I want to implement a method "searchForename" and "searchSurename" which search element which i added before with "insert". I looked at other implementations with ArrayList which search objects or elements,but mostly they are really confusing me because too much code w/o any Explanation.

THIRD EDIT WITH NEW QUESTIONS!:

Third try:

import java.util.ArrayList;


public class Adressbook {

    private ArrayList<Adress> adresses = null;

    public Adressbook(){
        adresses = new ArrayList<Adress>();
    }

    public void insert(Adress adress){
        adresses.add(new Adress("Marvin","Wildman","Blastreet",9,12345,"Blatown"));
        adresses.add(new Adress("Anne","Wildman","Woodstreet",10,6789,"Exampletown"));
        adresses.add(new Adress("William","Wildman","Eaglestreet",11,73975,"Blubvalley"));
    }


    public void searchSurename(String surename){
        for(Adress s: adresses){
            if("Green".equals(surename)){
            System.out.println(s);
            }
        }

    }

    public void searchForename(String forename){
        for(Adress s: adresses){
            if("Anne".equals(forename)){
            System.out.println(s);
            }
        }
    }

    public String toString(){
        return null;

    }

}

I have few questions:

1.How does the toString method in Adressbook look like?

2.How does the toString at Adress class Look like ?

3.Does the Constructor looks correct in the Adress class?

4.Can i implement the searching method easier/more efficient than this? If it is not correct,how can i Change it?

Forgot my class Adress:

public class Adress {
    public static String forename;
    public static String surename;
    public static String street;
    public static int houseno;
    public static int code;
    public static String state;



    public Adress(String forename, String surename, String street, int houseno, int code,String state){
        this.forename = forename;
        this.surename = surename;
        this.street = street;
        this.houseno = houseno;
        this.code = code;
        this.state = state;
    }



    public String toString(){
        return null;
    }

}
James Rich
  • 159
  • 1
  • 3
  • 9

1 Answers1

4

Your method is a static method and that's why you can't use the this in a static context as there is no object instance in a call of a static method.

public static String searchSurename // static method

You need to remove the static from your method declaration.

In case you can't do the above change, then you'll have to make your ArrayList adresses as static.

Also, as a side note, use the equals() for String value comparisons. == is for object refernce comparison.

if(this.adresses.get(i).getSurename().equals(surename)) {
Rahul
  • 44,383
  • 11
  • 84
  • 103