I need help to create 2 instance variables of type Person,that Takes data from the array csv and put it in the instance variables p1 and p2.
If i put data directly, it would be like that:
Person p1= new Person("John","Sina",new Adress("38",80331,"Munich","Germany"),"09.12.1989",))
Person p2= new Person("Brad","Pitt",new Adress("56", 70173,"Stuttgart","Germany"),"01.02.1972",))
but i have to take data from the array csv.
public class Address {
private String houseNumber;
private int zipCode;
private String city;
private String country;
public Address(String housenum, int zipCode, String city, String country) {
this.houseNumber = housenum;
this.zipCode = zipCode;
this.city = city;
this.country = country;
}
}
public class Person {
private String firstname;
private String lastname;
private Address address;
private String dateOfBirth;
public Person(String firstname, String lastname, Address address, String dateOfBirth) {
this.firstname = firstname;
this.lastname = lastname;
this.address = address;
this.dateOfBirth = dateOfBirth;
}
}
public class MyApplication {
public static void main(String[] args) {
String[] csv = {"John Cena, 38;80331;Munich;Germany ,09.12.1989",
"Brad Pitt, 56;70173;Stuttgart;Germany ,01.02.1972"};
for (int i = 0; i < csv.length; i ) {
String csv_row = csv[i];
}
}
}
CodePudding user response:
You should use .split(delimiter)
more than once in your code to process the string.
Also, you should use .trim()
method to get rid of whitespaces.
To be more clear, your code should look like:
final int ADDRESS_INDEX = 1;
String[] csv = {"John Cena, 38;80331;Munich;Germany ,09.12.1989",
"Brad Pitt, 56;70173;Stuttgart;Germany ,01.02.1972"};
for(String row : csv){ //for each string in the string array.
String[] csv_person = row.split(","); //the components of a person(name, address, birthdate)
String[] csv_address = csv_person[ADDRESS_INDEX].trim().split(";"); //the components of the address
String[] csv_person_name = csv_person[0].split(" "); //the components of the name(first and last names)
Person p = new Person(csv_person_name[0],csv_person_name[1], new Adress(csv_address[0],csv_address[1],csv_address[2],csv_address[3], csv_person[2]));
}
CodePudding user response:
Use a StringTokenizer like so:
for (int i = 0; i < csv.length; i ) {
String csv_row = csv[i];
StringTokenizer st = new StringTokenizer(csv_row, ";");
String firstname = st.nextToken();
String lastname = st.nextToken();
// For the Address try to apply the same splitting as for Person - I throw away this token on purpose now
Address address = null; st.nextToken();
String dateOfBirth = st.nextToken();
Person p = new Person(firstname, lastname, address, dateOfBirth);
// do whatever you want with this person
}