Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.io.*; //refer6.3.2 and 6.4.1
- class Ass1
- {
- public static void main (String[] args) //this is the main method
- {
- int agecount = 0; // declare variable, agecount for counting the line and documents
- try{ // try is to open the file
- File fileopen = new File("ages.txt"); // just open the ages.txt[refer6.4.1]
- Scanner agefilescanner = new Scanner(fileopen); // to read or scan the file-ages.txt
- while (agefilescanner.hasNext())//this is the loop for counting the number of line[refer 6.4.1]
- {
- agecount = agecount + 1; //increment for the counter
- agefilescanner.next(); // goes to the next line
- }
- agefilescanner.close(); // to close the scanner
- } catch(FileNotFoundException e) //in case the file doe not exist
- {
- }
- System.out.println("age.txt contains " + agecount + " line");
- int buffer[] = new int[agecount]; //to declare the array, in this case use BUFFER
- try{
- File fileopen1 = new File("ages.txt");
- Scanner agefilescanner1 = new Scanner(fileopen1);
- int counter = 0; // declared int counter
- while (agefilescanner1.hasNextLine()) //loop for second files
- {
- buffer[counter] = agefilescanner1.nextInt();
- counter = counter+1; //increases the counter, to the sum
- }
- } catch (FileNotFoundException e) //in case the ages.txt doesnot exist, show an error
- {
- }
- int sum =0; //refer 5.3.3 Iterating over arrays with 'for' statements
- for (int i = 0; i < buffer.length; i++) //refer5.3.3]
- sum += buffer[i];
- System.out.println("The sum is = " + sum);//for the sum
- System.out.println("The mean is = " + sum/agecount);// this is for the calculation of mean
- for (int i = 0; i < buffer.length-1; i++)
- {
- for (int j = 1; j < buffer.length; j++)
- {
- if (buffer[i] == buffer[j])
- {
- System.out.println(buffer[i]);
- }
- }
- }
- int middle = buffer.length/2;
- int median = 0;
- if (buffer.length%2 == 1){
- median = buffer[middle];
- }
- else
- {
- median = buffer[middle-1] + buffer[middle] / 2;
- }
- System.out.println( "The median is = "+ median);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement