I have this code and I receive an error when I run the program. Am I doing something wrong with this?
import java.io.*;
import java.util.*;
public class countLines {
public static void main(String[] args) throws Exception {
int count = 0;
int word = 0;
File f = new File("file.txt");
Scanner input = new Scanner(f);
while(input.hasNext()){
String words = input.next();
word++;
}
while (input.hasNextLine()) {
input.nextLine();
count++;
}
input.close();
System.out.println("Number of Line: " + count);
System.out.println("This file has " + word + " words.");
}
}
In your first
whileloop, you are reading your file, then youcloseit. Then, in your nextwhileloop you attempt to read from the file again. This will trigger an error, since the file is closed!