import java.util.Scanner;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import javax.swing.JFileChooser;

public class FileOps
{   // main methid averages reads all doubles in a file 
    // named numbers2.dat
    // each number is printed out as it is read
    // the average of the numbers is printed out after 
    // all tokens in the file have been read
    public static void main(String[] args) throws FileNotFoundException{
        Scanner s = new Scanner( new File("numbers2.dat") );
        
        double x;
        double total = 0;
        int i = 0;
        while( s.hasNext() ){
            if( s.hasNextDouble() ){
                x = s.nextDouble();
                total += x;
                i++;
                System.out.println("number " + i + " = " + x );
            } else {
                s.next();
            }
        }
        System.out.println("Total is " + total);
        System.out.println("Read in " + i + " doubles.");
        System.out.println("Average value is " + total / i);
    }
    
    // method that reads in ints in a file
    // ints are temps
    // print out difference between previous temp and current temp
    public static void readTemps() throws FileNotFoundException{
        Scanner s = new Scanner( new File("temps.txt") );
        int current;
        int previous = s.nextInt();
        while( s.hasNextInt() ){
            current = s.nextInt();
            System.out.println( "Temp difference is " + (previous - current) );
            previous = current;
        }
           
    }
    
    // method that allows user to select a file and prints out file
    // 1 line at a time
    public static void showFile() throws FileNotFoundException{
        File f = getFile();
        System.out.println( f );
        Scanner fileScanner = new Scanner( f );
        Scanner keyboard = new Scanner( System.in );
        System.out.println( "Press enter to see next line or B to quit: ");
        String response = "";
        while( response.length() == 0 && fileScanner.hasNextLine() ){
            System.out.println( fileScanner.nextLine() );
            response = keyboard.nextLine();
        }
    }
    
    // method to choose a file using a traditional window
    public static File getFile(){
        // create a GUI window to pick the text to evaluate
        JFileChooser chooser = new JFileChooser(".");
        int retval = chooser.showOpenDialog(null);
        File f =null;
        chooser.grabFocus();
        if (retval == JFileChooser.APPROVE_OPTION)
           f = chooser.getSelectedFile();
        return f;
    }
}
