-1

https://i.stack.imgur.com/Daxvo.png

So this is my assignment. I was able to split the input using the split() method, which created an array, splitArray. But the problem is, I don't know how to transfer the contents of the splitArray to the phoneNumberVec and nameVec array.

splitArray[] data:   
Joe
123-5432
Linda
983-4123
Frank
867-5309

Is there a way to put the names into one array and the numbers in another?

I hope I was clear on my question, I'm new to this whole thing! Thank you!

Mr. Discuss
  • 355
  • 1
  • 4
  • 13
  • Take a look at https://stackoverflow.com/questions/5785745/make-copy-of-an-array or search the web for `Java collections array` – Mark Stewart Sep 08 '20 at 21:27

1 Answers1

0

This is pretty simple. I think it's more comfortable to use Scanner instead of string split:

public static void main(String[] args) {
    String contactList = "3 Joe 123-5432 Linda 983-41-23 Frank 867-5309";
    String contactName = "Frank";

    System.out.println(getPhoneNumber(contactList, contactName));
}

public static String getPhoneNumber(String contactList, String contactName) {
    try (Scanner scan = new Scanner(contactList)) {
        int N = scan.nextInt();
        String[] nameVec = new String[N];
        String[] phoneNumberVec = new String[N];

        for (int i = 0; i < N; i++) {
            nameVec[i] = scan.next();
            phoneNumberVec[i] = scan.next();
        }

        return getPhoneNumber(nameVec, phoneNumberVec, contactName, N);
    }
}

public static String getPhoneNumber(String[] nameVec, String[] phoneNumberVec, String contactName, int arraySize) {
    for (int i = 0; i < arraySize; i++)
        if (nameVec[i].equals(contactName))
            return phoneNumberVec[i];
    return "<not found>";
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35