In: Computer Science
Write a program which reads an input file. It should assume that all values in the input file are integers written in decimal. Your program should read all integers from the file and print their sum, maximum value, minimum value, and average. Use the FileClient class here (from a previous reading) as an example. You'll need to create a file to be used as input to test your program, as well. Your program should work whether the integers are separated by spaces, new lines, tabs or a mix of the three (but it does not need to work with other delimiters, like commas). In other words, it should work as long as the integers are separated only by white space characters (this is what the Scanner's next<primitive> functions do).
To convert individual integers written in the file from their string from to int form, find and use an appropriate method in the Integer wrapper class.
import java.io.File; import java.util.Scanner; class FileClient { public static void main(String[] args) throws java.io.FileNotFoundException { File inputFile = new File("input.txt"); Scanner inputFileScanner = new Scanner(inputFile); String nextWord = ""; boolean keepLooping = inputFileScanner.hasNext(); while ( keepLooping ) { nextWord = inputFileScanner.next(); System.out.println( nextWord ); keepLooping = inputFileScanner.hasNext(); } } }
import java.io.File;
import java.util.Scanner;
public class FileClient
{
public static void main(String[] args) throws
java.io.FileNotFoundException
{
File inputFile = new File("input.txt");
Scanner inputFileScanner = new Scanner(inputFile);
String nextWord = "";
int sum=0,min=Integer.MAX_VALUE,max=-1,count=0;
boolean keepLooping = inputFileScanner.hasNext();
while ( keepLooping )
{
nextWord = inputFileScanner.next();
System.out.println( nextWord );
int n =Integer.valueOf(nextWord.trim());
sum+=n;
count++;
if(n>max)
max=n;
if(n<min)
min=n;
keepLooping = inputFileScanner.hasNext();
}
double avg = sum/(double)count;
System.out.println("Sum: "+sum);
System.out.println("Avg: "+avg);
System.out.println("Max: "+max);
System.out.println("Min: "+min);
}
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me