Just would like to say this program has defeated me in almost everyway. What I need to do is input a .txt file which contains this
There should be 59 characters 13 words and 6 lines in this file.
dont know how to format that to 6 lines.
The program counts the lines but says there are 78 words in the text file, not 13. Which is 6*13 = 78.
How can I get it to only read the line once.. hence reading 13 words not 13*6. The program seems to be counting the words that many times. (comments are put in for guidance by the proffesor).
package inputoutput;
import java.util.*;
import java.io.*;
public class input {
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(System.in);
String name;
int lineCount = 0;
int wordCount = 0;
System.out.println("Please type the file you want to read in: ");
name = s.nextLine();
// create a Scanner object to read the actual text file
File input = new File("C:\\Users\\Ceri\\workspace1\\inputoutput\\src\\inputoutput\\" + name + ".txt");
Scanner in = new Scanner(input);
while (in.hasNextLine()){ // enter while loop if there is a complete line available
// increase line counter variable
lineCount++;
// read in next line using Scanner object, inFile
in.nextLine();
// create another Scanner object in order to scan the line word by word
Scanner word = new Scanner(input);
// use while loop to scan individual words, increase word counter
while(word.hasNext()){
// increase word counter
wordCount++;
// Scanner move to next word
word.next();
}
word.close();
// count number of chars including space but not line break by using the length() method of the String class and increment character counter
}
in.close();
System.out.print("Lines " + lineCount + " "+ "Words " + wordCount);
}