gratiartis
Posts: 8
Nickname: gratiartis
Registered: Sep, 2003
|
|
Re: A simple question
|
Posted: Sep 17, 2003 8:56 AM
|
|
> while (str != null) { > System.out.print("> prompt "); > str = in.readLine(); > process(str);
> what do i put where it says process so that i can read > specific words in a text file.
It looks as though you are reading from the file line by line. Keeping things simple, I'll assume that you have a text file containing comma separated values. Hence a line might look like:
12,3,68,83,2,88,39
You have just created a String (str = "12,3,68,83,2,88,39") based on the contents of this line. In your 'process' method you can then use the 'split' method of the String class. Note that this 'split' method is recent (since 1.4), so if you are working with an earlier version of the JDK then you should use StringTokenizer for the same job. The following is a trivial example of how to use each of these:
// Initial value of String
String str = "12,3,68,83,2,88,39" ;
System.out.println( "Initial String=\"" + str + "\"" ) ;
// Using String.split()
String[] items = str.split( "," ) ;
for ( int i = 0 ; i < items.length ; i++ )
System.out.println( "items[" + i + "]=" + items[i] ) ;
// Using StringTokenizer
StringTokenizer st = new StringTokenizer( str, "," ) ;
String[] tokenizedItems = new String[ st.countTokens() ] ;
int j = 0 ;
while ( st.hasMoreTokens() ) {
tokenizedItems[j] = st.nextToken() ;
j++ ;
}
for ( int i = 0 ; i < tokenizedItems.length ; i++ )
System.out.println( "tokenizedItems[" + i + "]=" + tokenizedItems[i] ) ;
|
|