Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Putting Tokens into an Array

 
Anica Jovanova
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please somebody help us with our project. We have 4 tokens of different data types and we are trying to put them into an array. How do we do that? There is a Person object with 4 parametars all different types: long, String, and int. We tokenized them and we are trying to put them into an array of this Person object. How do we do that?
Thanks a lot. Your help is really appreciated.
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Anica,
Welcome to JavaRanch. If I understand right, you want to put an int, a long and a String in the same array, is that right? Well, you can't do that. What you can do is wrap the two primitives in Object wrappers and declare an Object[] array to store them like this:

Michael Morris
 
Anica Jovanova
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for the quick respond. OK, you have inseted the elements into the array manually, but we are reading them from a file using that bufferedReader thing. And once we do the StringTokenizer() method, to split te four types of data we have, we don't know how to insert them into an array of objects.
here is what we've done so far:
import java.io.*;
import java.util.*;
public class SimpleStringToken {
public static void main(String[] args) throws IOException {
File inputFile = new File(args [0]);
FileReader in = new FileReader(inputFile);
BufferedReader d = new BufferedReader(in);
String line;
while ((line = d.readLine()) != null) {
System.out.println(line);
StringTokenizer st = new StringTokenizer(line);
long id = Long.parseLong(st.nextToken());
String last = (st.nextToken());
String first = (st.nextToken());
int age = Integer.parseInt(st.nextToken());
System.out.println("id = " + id
+ " last name = " + last
+ " first name = " + first
+ " age = " + age);
}
in.close();
}
}
And we have also created a Person object having a constructor like this:
Person(long id, String last, String first, int age)
Does the question make sense now?
Thanks a lot, I'm really happy to have found this site today.
 
Wirianto Djunaidi
Ranch Hand
Posts: 210
Ruby Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't really know exactly what you need, but I'm just guessing you want an array of Person with attributes that are read from a file.
From your code I'll say it's easier to use ArrayList.
So you'll have:

Hope that's what you need.
-Ryo
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic