Reading text files and the calculating averages from it
Ok so i am working on an assingment where I have to read data from text file and the calculate the average of both classes in each major. There are two majors CS and Math and two scores listed for each major - the Math class score and the Java class score.
I got to the point where it reads every line of the data.txt file and the prints the data neatly by line.
Where i am stuck is , I have to figure out the averages of each Major and the classes seperately for each major.
the data.txt looks like this.
John Smith
CS
89
99
Jonathan Sou
MATH
78
98
James Scott
CS
78
87
Adam Brown
MATH
99
59
Peter Paulson
CS
78
100
here is my current code so far.
Code java:
import java.io.File; // for File
import java.io.FileNotFoundException;
import java.util.Scanner; // for Scanner
public class TEST
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner input = new Scanner(new File("data.txt"));
String firstname, lastname;
String major;
while (input.hasNext())
{
firstname = input.next();
lastname = input.next();
major = input.next();
double math = input.nextDouble();
double java = input.nextDouble();
System.out.println(firstname + " " + lastname + ", " + " " + major + ", " + math + ", " + java);
}
input.close();
}
}
CURRENT OUTPUT
John Smith, CS, 89.0, 99.0
Jonathan Sou, MATH, 78.0, 98.0
James Scott, CS, 78.0, 87.0
Adam Brown, MATH, 99.0, 59.0
Peter Paulson, CS, 78.0, 100.0
WHAT I NEED OUTPUT TO BE
John Smith, CS, 89.0, 99.0
Jonathan Sou, MATH, 78.0, 98.0
James Scott, CS, 78.0, 87.0
Adam Brown, MATH, 99.0, 59.0
Peter Paulson, CS, 78.0, 100.0
----- ---------- ----------
MATH Math AVG= 88.5 Java AVG= 78.5
CS Math AVG= 81.66666666666667 Java AVG= 95.33333333333333
Can someone point on the right path?
Re: Reading text files and the calculating averages from it
Please post the output from the program.
Do you know how to add the value of one variable to another? Use that technique to add up the values and to count the number of values that were read.
After all the lines have been read, compute the averages and print them.
Please edit your post and wrap your code with code tags:
[code=java]
<YOUR CODE HERE>
[/code]
to get highlighting and preserve formatting.
Re: Reading text files and the calculating averages from it
I had the output listed. I have edited to wrap the code. thanks
Where I am having issues wrapping my head around, is how do i tell it to look and add the scores that are listed on the lines for each major. Like how could i tell it to sum up and average the line that lists scores for CS Major and line that lists scores for the Math Major.
Re: Reading text files and the calculating averages from it
Quote:
scores that are listed on the lines
The scores are in the variables that were read.
Do you know how to add the value of one variable to another?
total = total + detail; // add detail to the total