Re-enforce loops & decision structures by applying them to file input. Read data
ID: 642372 • Letter: R
Question
Re-enforce loops & decision structures by applying them to file input.
Read data (integers) from a file as part of a loop (and print the number after reading it), with an unknown amount of data items in the input, print the smallest number, the largest number, the sum of the numbers, and the average of the numbers. Note, average should be data-type double.
input numbers from a file, compute and print statistics
name your input file pd06.txt
P.S. i am using absolute java book chapter 1-4 and first year student, so please refrain from using expert knowledge i would not be able to use, and thanks for your help
Explanation / Answer
//Java program read a text file contains integer values and
//prints the smallest ,largest ,sum and average values.
//ReadFile.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile
{
public static void main(String[] args)
{
int elementsCount=0;
//set max value to integer
int smallest=Integer.MAX_VALUE;
//set min value to integer
int largest=Integer.MIN_VALUE;
int sum=0;
double average = 0.0;
//Create a File class object
File file=null;
Scanner fileScanner=null;
String fileName="pd06.txt";
try
{
//Create an instance of File class
file=new File(fileName);
//create a scanner class object
fileScanner=new Scanner(file);
//assume first number is smallest
//and largest be the first number
//read data from file
while (fileScanner.hasNext())
{
int value=fileScanner.nextInt();
elementsCount++;
//check if the value is less than smallest
if(value<smallest)
smallest=value;
//check if the value is larger than largest value
if(value>largest)
largest=value;
//find sum of values
sum+=value;
}
//print smallest value
System.out.println("Smallest Number : "+smallest);
//print largest value
System.out.println("Largest Number : "+largest);
//print sum of values
System.out.println("Sum Of Numbers : "+sum);
//print average value
System.out.println("Average of Number :"+sum/(double)elementsCount);
}
//Catch the exception if file not found
catch (FileNotFoundException e)
{
System.out.println("File Not Found");
}
}
}
---------------------------------------------------------------
Input text file:
pd06.txt
10
20
30
40
50
Sample output:
Smallest Number : 10
Largest Number : 50
Sum Of Numbers : 150
Average of Number :30.0
Hope this helps you
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.