Thursday, November 15, 2012

Javascript Document Read and Write




// Christopher Smith
// Lab 7 File I/O (read and write)
//


import java.util.Scanner; // for input from a source keyboard, txt, etc
import java.io.*;         // for handling files

public class lab7 {
  public static void main(String[] args) {
     Scanner input = null;          // must initialize with null
     PrintWriter output = null;     // must initialize with null
     int number; //creating placeholder number for read in values
     int sum = 0;  //initialize, clear possible remnant data

     try {             // tests if the two files are there
        input = new Scanner( new FileInputStream( "input.txt" ) );
        output = new PrintWriter( new FileOutputStream( "output.txt" ) );
     }
     catch ( FileNotFoundException e ) {  // if 'try' fails
        System.out.println( "Can't read/write files." );
        System.exit(0);
     }

/******************************************************************/
/*Start of loop to read file and sum of numbers********************/
/*****************************************************************/
     
int count = 0 ; //defining and initializing count for loop
int max = 0;//max initial value
int min = 999;//min initial value
int avg = 0; //average of numbers

while (input.hasNextInt()) //checks for next line
{
number = input.nextInt(); // read in an integer
      System.out.println( "Read in: " + number );//display first number read
      sum = sum + number; //sum number read with existing sum
      output.println( "Sum is now: " + sum );
count = count + 1; //cycles count for average
if (number > max)//determines max
{
max = number;//sets max
}
if (number < min)//determines min
{
min = number; //sets min
}
}
avg = sum/count; //determines avg sum divided count

     output.println("The Max Int is "+max);//prints max value
output.println("The Min Int is "+min);//prints min value
output.println("The Avg of it all is "+avg); //prints avg

// close the files:
     input.close();  // close input file
     output.close(); // close output file

     System.out.println("See what's in the output.txt!");
  }
}

No comments:

Post a Comment