Reputation: 1820
I have a text file I am trying to break up with string tokenizer. Here is a few lines of the text file:
Mary Smith 1
James Johnson 2
Patricia Williams 3
I am trying to break up into first name, last name and Customer ID.
I have so far been able to do that but it stops after mary smith.
Here is my code:
public static void createCustomerList(BufferedReader infileCust,
CustomerList customerList) throws IOException
{
String firstName;
String lastName;
int custId;
//take first line of strings before breaking them up to first last and cust ID
String StringToBreak = infileCust.readLine();
//split up the string with string tokenizer
StringTokenizer st = new StringTokenizer(StringToBreak);
firstName = st.nextToken();
while(st.hasMoreElements())
{
lastName = st.nextToken();
custId = Integer.parseInt(st.nextToken());
CustomerElement CustomerObject = new CustomerElement();
CustomerObject.setCustInfo(firstName,lastName,custId);
customerList.addToList(CustomerObject);
}
}
Upvotes: 1
Views: 1853
Reputation: 61
For the outer loop, you need to store the contents of the current line in the stringToBreak variable so that you can access it inside the loop. You need a new StringTokenizer for each line so it needs to be inside the loop.
String stringToBreak = null;
while ((stringToBreak = infileCust.readLine()) != null) {
//split up the string with string tokenizer
StringTokenizer st = new StringTokenizer(stringToBreak);
firstName = st.nextToken();
lastName = st.nextToken();
custId = Integer.parseInt(st.nextToken());
}
Upvotes: 1
Reputation: 13841
String StringToBreak = infileCust.readLine();
reads the FIRST line from the file. And you feed the StringTokenizer with it. It's normal that StringTokenized doesn't find more tokens.
You have to create a second loop enclosing all this to read every line. It is:
outer loop: readLine until it gets null {
create a StringTokenizer that consumes *current* line
inner loop: nextToken until !hasMoreElements()
}
Well, indeed you don't need to do an inner loop because you have three different fields. It's enough with:
name = st.nextToken();
lastName = st.nextToken();
id = st.nextToken;
Upvotes: 3
Reputation: 396
First off, you want to look at your loop, specifically how you have firstName outside of the loop so that is going to throw all of you tokens off. You will be trying to create new customer objects without enough information.
Upvotes: 0