Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Firstly, manually create a file Numbers.txt and fill it with integers, one below

ID: 3681364 • Letter: F

Question

Firstly, manually create a file Numbers.txt and fill it with integers, one below the other. Write a program that reads ANY sequence of integers (can be positive, 0 or negative) from this file. Using a looping construct, you will read numbers from the file till end of the file is reached. Calculate the largest and the smallest numbers among the data in the file. Your code must display both of those on the terminal screen along with total count of numbers present in the sequence and the average (always print two digits after decimal point) of all numbers in the file.

Count =

Average =

Largest Value =

Smallest Value =

Note: Keep in mind that the file can have any number of integers and the count can only be determined by reading the entire file.

Explanation / Answer

package assignment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class IntegersFromFile {
   public static void main(String args[]) {
       String strFilePath = "D:/ravi/Cheg/Numbers.txt";
       try {
          
           Scanner scanner = new Scanner(new File(strFilePath));
           int count = 0;
           float avg = 0;
           int largest = 0;
           int smallest = 0;
           int num = 0;
           int sum = 0;
           String str = null;
           while(scanner.hasNext()){
               str = scanner.next();
               if(!"".equals(str.trim())) {
                   num = Integer.parseInt(str.trim());
                   System.out.println(num);
                   count++;
                   sum += num;
                   if(num > largest)
                       largest = num;
                   if(num < smallest)
                       smallest = num;
               }
              
           }
          
           avg = sum / count;
           System.out.println(" Count : "+count+" Average : "+avg+" Largest : "+largest+" Smallest:"+smallest);
       } catch (FileNotFoundException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
   }
}

----Input---------

10 20
-2
3
4
-20
40 59 -70
-60
20
43
50

--output-------------

10
20
-2
3
4
-20
40
59
-70
-60
20
43
50
Count : 13 Average : 7.0 Largest : 59 Smallest:-70