|
CS160 Class Wiki Instructors |
Main /
Lab13Solution
import java.io.*; // for File, FileNotFoundException
import java.util.*; // for Scanner
public class Lab13
{
public static void main(String[] args) throws FileNotFoundException
{
int lines = 0, words = 0, characters = 0;
//Get the filename from the user:
Scanner userscan = new Scanner(System.in);
System.out.print("Enter a file name: ");
String filename = userscan.nextLine();
//Open the file
File f = new File(filename);
if(!f.exists())//Checks to see if the file exists
{
System.out.println(filename + " does not exist!");
return;
}
Scanner filescan = new Scanner(f);
//Read one line at a time
while(filescan.hasNextLine())
{
String line = filescan.nextLine();
Scanner linescan = new Scanner(line);
//read one word at a time
while(linescan.hasNext())
{
linescan.next();
words++;
}
lines++;
characters += line.length();
}
System.out.println("The file has " + lines + " lines, " + words + " words and " + characters + " characters.");
}
}
|