1

I have this class ENTRY that has types of PERSON and PHONE (both separated classes. In my main class, i use Scanner to take data from txt file and insert it into ENTRY creator method. The problem is that i only get PHONE variable right, while PERSON gets "nulled". Individualy, when i create PERSON via same Scanner and txt file, i get good result for type PERSON.

Here are parts of code:

In class PERSON:

public static PERSON loadPerson(Scanner sc)
    {
        return new PERSON(sc.next(), sc.next());
    }

In class PHONE:

public static PHONE loadPhone(Scanner sc){

        return new PHONE(sc.next(), sc.next());
    }

In class ENTRY:

public static ENTRY loadEntry(Scanner sc)
    {
        return new ENTRY(PERSON.loadPerson(sc), PHONE.loadPhone(sc));
    }

and in main test class i write:

E = ENTRY.loadEntry(sc);

txt file line 1 looks like this: "Gavrilo Aleksic 012 221788" (without quotes). He is supposed to take first and last name into PERSON constuctor and two numbers into PHONE const. They look like:

PERSON:

private String name;
private String surname;

public PERSON(String name, String surname)
    {
        this.name = name;
        this.surname = surname;
    } 

PHONE:

private String local, area;
public PHONE(String area, String local)
    {
        this.area = area;
        this.local = local;
    }

ENTRY:

public static ENTRY loadEntry(Scanner sc)
    {
        return new ENRTY(PERSON.loadPerson(sc), PHONE.loadPhone(sc));
    }

1 Answers1

0

Objects in Java are passed by reference.

As I understand from your question, you want to initialize the instances of Person and Phone when you do -

     new Entry()

And, the Entry class structure is something like

    class Entry {
       Person p;
       Phone ph;
    }

add a constructor to your Entry class

    Entry (Person p, Phone ph) {
       this.p = p;
       this.ph = ph;
    }

Now, in you main method -

    Scanner s = new Scanner("File path to read from");
    Entry e = Entry.loadEntry(sc);
    s.close();

Inside, loadEntry method

    public static Entry loadEntry (Scanner sc) {
        if (s.hasNextLine()) {
            String[] temp = s.nextLine().split("\\s");

            //assuming file contains 'Gavrilo Aleksic 012 221788'
            Person p = new Person(temp[0], temp[1]);
            Phone ph = new Phone(temp[2], temp[3]);

            return new ENRTY(p, ph);
        }
        return null;
    }
Community
  • 1
  • 1
Tirath
  • 2,294
  • 18
  • 27