Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2014
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.21 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.io.*; //refer6.3.2 and 6.4.1
  3.  
  4. class Ass1
  5. {
  6.  public static void main (String[] args) //this is the main method
  7.   {
  8.   int agecount = 0; // declare variable, agecount for counting the line and documents
  9.     try{  // try is to open the file
  10.     File fileopen = new File("ages.txt"); // just open the ages.txt[refer6.4.1]
  11.     Scanner agefilescanner = new Scanner(fileopen); // to read or scan the file-ages.txt
  12.    
  13.     while (agefilescanner.hasNext())//this is the loop for counting the number of line[refer 6.4.1]
  14.     {
  15.     agecount = agecount + 1; //increment for the counter
  16.     agefilescanner.next(); // goes to the next line
  17.     }
  18.     agefilescanner.close(); // to close the scanner
  19.     } catch(FileNotFoundException e) //in case the file doe not exist
  20.     {
  21.     }
  22.     System.out.println("age.txt contains " + agecount + " line");
  23.     int buffer[] = new int[agecount]; //to declare the array, in this case use BUFFER
  24.    
  25.     try{
  26.     File fileopen1 = new File("ages.txt");
  27.     Scanner agefilescanner1 = new Scanner(fileopen1);
  28.    
  29.     int counter = 0; // declared int counter
  30.     while (agefilescanner1.hasNextLine())  //loop for second files
  31.     {
  32.       buffer[counter] = agefilescanner1.nextInt();
  33.       counter = counter+1; //increases the counter, to the sum
  34.       }
  35.       } catch (FileNotFoundException e) //in case the ages.txt doesnot exist, show an error
  36.       {
  37.       }
  38.       int sum =0; //refer 5.3.3 Iterating over arrays with 'for' statements
  39.      
  40.       for (int i = 0; i < buffer.length; i++) //refer5.3.3]
  41.     sum +=  buffer[i];
  42.     System.out.println("The sum is = " + sum);//for the sum
  43.     System.out.println("The mean is = " + sum/agecount);// this is for the calculation of mean
  44.    
  45.     for (int i = 0; i < buffer.length-1; i++)
  46.     {
  47.     for (int j = 1; j < buffer.length; j++)
  48.     {
  49.     if (buffer[i] == buffer[j])
  50.     {
  51.     System.out.println(buffer[i]);
  52.     }
  53.     }
  54.     }
  55.    
  56.    
  57.       int middle = buffer.length/2;
  58.       int median = 0;
  59.       if (buffer.length%2 == 1){
  60.       median = buffer[middle];
  61.       }
  62.       else
  63.       {
  64.     median = buffer[middle-1] + buffer[middle] / 2;
  65.       }
  66.       System.out.println( "The median is = "+ median);
  67.        
  68.    
  69.    
  70.    
  71.  
  72.   }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement