The method is to return an array counting the number of lines, words and characters in a document. After running it through a test file I am still receiving some errors.
public static int[] wc(Reader in) throws IOException {
int data = in.read();
int charcounter = 0;
int linecounter = 0;
int wordcounter = 0;
boolean previouswhitespace = false;
while (data != -1){
if (((char) data == '\n')){
linecounter++;
}
if (!(Character.isWhitespace((char) data))){
charcounter++;
if ((previouswhitespace == true) || (wordcounter == 0)){
previouswhitespace = false;
wordcounter++;
}
}
else if ((Character.isWhitespace((char) data))){
previouswhitespace = true;
}
data = in.read();
}
int[] array = {linecounter, wordcounter, charcounter};
return array;
}
//To choose the file
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
String file_path = file.getAbsolutePath();
char[] c;
String [] words;
int charCounter = 0 ,wordsCounter = 0, lineCounter = 0;
//try and catch for the BufferedReader
try{
String line;
BufferedReader reader = new BufferedReader(new FileReader(file_path));
while( (line = reader.readLine()) !=null){
c = line.replace(" ","").toCharArray();
charCounter+=c.length;
words = line.split(" ");
wordsCounter+=words.length;
lineCounter++;
}
}catch(Exception e){
// Handle the Exception
}
int array[] = {charCounter , wordsCounter, lineCounter};
Hope this is helping you!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.