In: Computer Science
Java question- Write a java program to process the number.txt
file. Then count the numbers and calculate the total average, even
numbers average, odd number average, then print the corresponding
information. The result should be displayed in the following
format
there are XX numebers in the file
there are xx even numbers
there are xx odd numbers
the total number average is xx
the odd number average is xx
the even number average is xx
I am having trouble using the printwriter and file classes to
read data. It keeps saying the file was not found when I know its
downloaded.
I also do not think I can upload the file here but any help is much
appreciated.
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class FileAverageStats { public static void main(String[] args) { File file = new File("number.txt"); try { Scanner fin = new Scanner(file); int count = 0, oddCount = 0, evenCount = 0, total = 0, oddTotal = 0, evenTotal = 0, num; while (fin.hasNextInt()) { num = fin.nextInt(); count++; total += num; if(num % 2 == 0) { evenCount++; evenTotal += num; } else { oddCount++; oddTotal += num; } } System.out.println("there are " + count + " numbers in the file"); System.out.println("there are " + evenCount + " even numbers"); System.out.println("there are " + oddCount + " odd numbers"); System.out.println("the total number average is " + (total / (double)count)); System.out.println("the odd number average is " + (oddTotal / (double)oddCount)); System.out.println("the even number average is " + (evenTotal / (double)evenCount)); fin.close(); } catch (FileNotFoundException e) { System.out.println(file.getAbsolutePath() + " does not exists"); System.out.println("Check if number.txt is in proper directory"); } } }