简体   繁体   中英

Calling a method from within another method of the same class

I have a number of methods which need to implement my add method, however I am not sure how to go about doing this, as all the methods are in the same class - ArrayPhoneDirectory.

Add method:

private void add(String name, String telno) {
    if (size >= capacity)
    {
        reallocate();
    }
    theDirectory[size] = new DirectoryEntry(name, telno);
    size = size +1;
}

The following are methods which require add to be called:

load:

public void loadData(String sourceName) {
    Scanner scan = new Scanner(sourceName).useDelimiter("\\Z");

    while (scan.hasNextLine()) {
        String name = scan.nextLine();
        String telno = scan.nextLine();

        DirectoryEntry newdir = new DirectoryEntry(name, telno);

        //ADD THE NEW ENTRY TO THE DIRECTORY
    }
}

addChangeEntry:

public String addChangeEntry(String name, String telno) {
    for (DirectoryEntry x : theDirectory) {
        if (x.getName().equals(name)) {
            x.setNumber(telno);
            return x.getNumber();
        } else {
           // add a new entry to theDirectory using method add   
        }
    }
    return null;
}

It is probably something very obvious, however I am still fairly new to java so any help as to how to call these methods would be much appreciated!

You can just call add(name, telno) and it will work.

In fact your add method is private, so it can only be called from inside the class.

For example, in your load method:

public void loadData(String sourceName) {
    Scanner scan = new Scanner(sourceName).useDelimiter("\\Z");

    while (scan.hasNextLine()) {
        String name = scan.nextLine();
        String telno = scan.nextLine();

        // You don't need this, add builds its own DirectoryEntry from name and telno
        // DirectoryEntry newdir = new DirectoryEntry(name, telno);

        add(name, telno);
    }
}

And you can do exactly the same in addChangeEntry

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM