mercredi 25 février 2015

How can the minimum and maximum of a list of integers in a .text file be determined?



My objective is to read a .text file filled with an unknown amount of integers and find the sum/average/min/and max. I have it down to finding the sum and average, I just need help finding the min and max from a .text file. Here is what I have so far.



public static void main(String[] args)
{
Scanner file = null; //initializes file to empty
int cnt=0;
int sum = 0;
double average;
try
{
//attempt to open file.
file = new Scanner(new FileInputStream("pd06.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File Not found. Error 404");
System.exit(2);
}

while(file.hasNextInt())
{

sum+=file.nextInt();//sums all numbers within the file
cnt++; // counts all numbers in file.
// Used in average.
}
average = (double)sum / cnt; //Average

System.out.println("There are "+cnt+" numbers in "
+ "the file.");
System.out.println("The sum of which is "+sum);
System.out.printf("The average of all %d numbers "
+ "is %.2f\n",cnt ,average);
}



Aucun commentaire:

Enregistrer un commentaire