Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Question on String Tokenizer .  RSS feed

Pallavi Chakraborty
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everybody,
I have an application which has two parts. It gets employee data from the user, SSN, firstname, lastname and stores it in a text file.
This data is stored in the format:
SSN: FirstName: LastName.
Then the String Tokenizer needs to get the individual parts of this using the delimiter:.
I am pasting the three files.
1.Employee1 - writes to the file
2.Employee App - calls Employee1
3.Employee2 - reads from file
The reading part using the String Tokenizer is not working. It is directly going to the catch statement.
I will really appreciate it if you can help me with this.

Ernest Friedman-Hill
author and iconoclast
Posts: 24217
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, it's hard to know where to start with this program. I suppose "with the immediate cause of the error" is one place: you call the file "EmpDetails.txt" in one place, and "filename.txt" in another, and so presumably there's an exception when the file is opened for reading. You'd know that if in your catch block (ALL YOUR CATCH BLOCKS!) you actually displayed the exception object using printStackTrace(), or at least getMessage(); this is a good general policy, and something to always try before asking here.
One other random comment, and then I'll leave well enough alone: the constructor that does nothing but write a record to a file is REALLY gross: constructors are supposed to initialize objects, not do otherwise unrelated work.
[ July 14, 2003: Message edited by: Ernest Friedman-Hill ]
Jaunty John
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
StringTokenizer is part of the java.util.* class; you need to import java.util.*;
The code below compiles and runs...
import java.util.*;
public class Employee2 {
public static void main(String args[]) throws IOException {
try {
FileReader fr = new FileReader("filename.txt"); //creating a File Reader Object

BufferedReader br = new BufferedReader(fr);

while(br.ready()) {
String line = br.readLine();
StringTokenizer st = new StringTokenizer(line, ":");//creating a System Tokenizer.
int SSn = Integer.parseInt(st.nextToken().trim());//get the SSn part
String firstname = st.nextToken().trim();//get the firstname part
String lastname = st.nextToken().trim();//get the lastname part
System.out.println("SSN=" + SSn + " Fname=" + firstname + " Lname=" + lastname);


catch(Exception e) {
System.out.print("Error now");
}//~public static void main(...
}//~public class Employee2...
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!