user3000731
user3000731

Reputation: 93

Parsing String to Object

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!

Upvotes: 0

Views: 92

Answers (3)

subash
subash

Reputation: 3140

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));
}

Upvotes: 0

blacktide
blacktide

Reputation: 12086

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));

Upvotes: 2

Alexis C.
Alexis C.

Reputation: 93842

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));

Upvotes: 3

Related Questions