how to ouput my file on number of lines?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Adam_Ibram
Posted On:   Monday, March 3, 2003 03:56 PM

Below is my program which takes a file as an input and output the same file but with a word in each line. e.g this is an example . . . import java.io.*; import java.util.*; import java.util.StringTokenizer; class displayLines { public static void main(String args[]) throws Exception { FileReader fr = new FileReader("tutorial2.txt"); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); while(line != null){ StringTokenizer st = new StringTokenizer(line, " "); while(st.hasMoreTokens()){ System.out.println(st.nextToken()); } line = br.readL   More>>

Below is my program which takes a file as an input and output the same file but with a word in each line. e.g
this
is
an
example
.
.
.



import java.io.*;
import java.util.*;
import java.util.StringTokenizer;

class displayLines {
public static void main(String args[]) throws Exception {
FileReader fr = new FileReader("tutorial2.txt");
BufferedReader br = new BufferedReader(fr);

String line = br.readLine();
while(line != null){
StringTokenizer st = new StringTokenizer(line, " ");
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
line = br.readLine();
}
}
}




I want the output displays each line with a sentence ending with a full stop rather than a single word, e.g:
This is an example.
and this is another example.

any body can advice please?

Regards

   <<Less

Re: how to ouput my file on number of lines?

Posted By:   David_Bates  
Posted On:   Thursday, March 6, 2003 05:29 AM

If I understand you correctly (by the way, when you post your code, put it between
 tags so it is formatted correctly), then you want to be able to print out a sentence at a time.  This isn't too bad.  All you have to do is set the delimiter of StringTokenizer to be the full-stop:

import java.util.*;
public class RunTest {
public static void main(String[] args) {
String str = "First sentence. Second Sentence. Third sentence.";
StringTokenizer st = new StringTokenizer(str, ".");
while (st.hasMoreTokens()) {
String sentence = st.nextToken();
System.out.println("Sentence: '" + sentence.trim() + ".'");
}
}
}

will output:

C:>java RunTest
Sentence: 'First sentence.'
Sentence: 'Second Sentence.'
Sentence: 'Third sentence.'

Note: The second argument to the StringTokenizer constructor dictates what the string delimiter.



Hope this helps,



David.
About | Sitemap | Contact