Reputation: 71
I am trying to read in information from an external file and print to the screen different stats about them. I was able to successfully track down the amount of lines and paragraphs but ran into trouble trying to find the total amount of words.
I noticed that when I take the second while loop and put it first, it gives me the correct amount of words but the wrong lines and paragraphs, but when I run it as it is now, it gives me the correct lines and paragraphs but the wrong words.
I would really appreciate your help in figuring out why this is so. Thank you!
int x = 0, words = 0, y = 0;
System.out.print("Name of the input file: ");
in = kbd.nextLine().toLowerCase();
System.out.println(" ");
// Set up connection to the input file
Scanner input = new Scanner(new FileReader(in));
// Set up connection to an output file
PrintWriter output = new PrintWriter(new FileOutputStream("datacopy.txt"));
int lineNum = 0;
while (input.hasNextLine()) {
String line;
line = input.nextLine();
if (line.length() == 0) {
x++;
}
output.println(line + "\n");
lineNum++;
}
while (input.hasNext()) {
String line = input.next();
words++;
}
System.out.println("Words: " + words);
System.out.println("Lines: " + lineNum);
System.out.println("Paragraphs " + --x);
System.out.println(" ");
System.out.println("Output file datacopy.txt created.");
Upvotes: 0
Views: 36
Reputation: 726489
The problem is that both loops below require the input
to be positioned at the start of file:
while (input.hasNextLine()) // count lines
while(input.hasNext()) // count words
Although "rewinding" the file and starting from the beginning is possible, it is not optimal. It is better to read the file line-by-line, and count words as you go.
Using the line
variable from the while (input.hasNextLine())
loop, split it into individual words, and add their number to the running total:
while (input.hasNextLine()) {
String line = input.nextLine();
output.println(line + "\n");
lineNum++;
if(line.length() == 0){
x++;
continue;
}
words += line.split("\\s+").length;
}
Upvotes: 1
Reputation: 59950
You have to re-initialize your input
in each loop :
Scanner input = new Scanner(new FileReader(in));
//loop1
input = new Scanner(new FileReader(in));//re-initialize it again
//loop2
Because in the second loop, your loop not start from the beginning, it will start from the end-point of the first loop.
Upvotes: 2