0

I am having trouble parsing a String into an object. I want to be able to take a String such as : "John Smith 1234" and parse it into a Person object (Person(String, String, int) )

To do this, I first tried turning the String into a String[] and splitting at the spaces. I can't figure out why this isn't working- I tried testing just this part of the method and I got this: [Ljava.lang.String;@1aa8c488

Here is my code:

public static Person parseToPerson(String s) {
    String first = "";
String last = "";
String ID = "";
String[] splitArray = s.split("\\s+");
splitArray[0] = first;
splitArray[1] = last;
splitArray[2] = ID;
System.out.println(splitArray);
return new Person(first, last, Integer.parseInt(ID));
}

Thank you!

0

3 Answers 3

3

I can't figure out why this isn't working

You should swap your assignments :

first = splitArray[0];
last = splitArray[1];
ID = splitArray[2];

I tried testing just this part of the method and I got this: [Ljava.lang.String;@1aa8c488

Since splitArray is an array, you see the string representation of the array itself and not the content of it. Use Arrays.#toString(java.lang.Object[]):

System.out.println(Arrays.toString(splitArray));
Sign up to request clarification or add additional context in comments.

Comments

2

It looks like you've swapped the assignments. Try this.

first = splitArray[0];
last = splitArray[1];
ID = splitArray[2];

You are not getting the output that you'd like though because you should use the Arrays.toString(splitArray) to output the array:

import java.util.Arrays;

System.out.println(Arrays.toString(splitArray));

Comments

0

like this...

public static Person parseToPerson(String s) {
    String first = "";
    String last = "";
    String ID = "";
    String[] splitArray = s.split("\\s+");
    first = splitArray[0];
    last = splitArray[1];
    ID = splitArray[2];
    System.out.println(splitArray);
    return new Person(first,last, Integer.parseInt(ID));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.