Hi all,
I am writing a program (weekly assignment) that takes numbers from a text file called Q2.txt, ignores white space, and gives the user a printout of the sum total and average of all the numbers in the text file.
I have it working, but i can only make it work for doubles or integers only.
I'll get full marks for what i have below, but for personal interest, i'd like to know how to make the program work for any and all number formats.
How can i make it work for both ints and doubles?
my Q2.txt is contains = 5.0 5.0 5.0 5.0
Program returns : Average = 5.0, total = 20.0
Thanks for any and all advice
EDIT: I rewrote my test file Q2.txt with a mix of doubles and ints and it worked.
So can i change my question to: Is this best practice? How can i improve this?
import java.io.*; import java.util.Scanner; public class Q2 { //Open main method and throw any exceptions. public static void main(String[] args) throws Exception { //input from file called Q2.txt Scanner input = new Scanner(new File("Q2.txt")); //initialise variables for total and counter double sum = 0.0; int counter = 0; //while there is still scores in the file unread, read them, add to the total and increment the counter while (input.hasNext()) { sum += input.nextDouble(); counter++; } //divide the sum by the counter double average = sum / counter; //print the results System.out.println("The total of the scores in Q2.txt is " + sum); System.out.println("The average of the scores in Q2.txt is " + average); //close user input input.close(); } }