Recent Changes - Search:

CS160

Class Wiki

Instructors



edit SideBar

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.");
    }
}
Edit - History - Print - Recent Changes - Search
Page last modified on November 20, 2008, at 10:33 PM MST