Java Calculate Average using a Loop

  • (2 Pages)
  • +
  • 1
  • 2

18 Replies - 22134 Views - Last Post: 29 October 2010 - 01:30 PM Rate Topic: -----

#1 starlite  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 22-October 10

Java Calculate Average using a Loop

Posted 22 October 2010 - 06:52 AM

I am writing a Java program that ask to read from a file, display the original data along with each player's average score and announce who is the highest average scoring player. The file contain information of one player per line, followed by a sentinel value -1. The problem I am having is displaying each line separately. Any assistant would be appreciated!

Example of file information:
Smith 13 20 8 12 -1
Burch 21 18 9 -1
Winorburg 9 14 14 23 25 -1
.....

Here is my ouput:
Smith 13.0 20.0 Players average: 13.0
Smith 20.0 8.0 Players average: 16.5
Smith 8.0 12.0 Players average: 13.666666666666666
Smith 12.0 -1.0 Players average: 13.25
Burch 21.0 18.0 Players average: 14.8
Burch 18.0 16.0 Players average: 15.333333333333334
Burch 16.0 -1.0 Players average: 15.428571428571429
Winorburg 9.0 14.0 Players average: 14.625
Winorburg 14.0 14.0 Players average: 14.555555555555555
Winorburg 14.0 23.0 Players average: 14.5
Winorburg 23.0 25.0 Players average: 15.272727272727273
Winorburg 25.0 -1.0 Players average: 16.083333333333332

Here is my code:
import java.util.Scanner;
import java.io.*;

public class PlayerAverage
{
    public static void main(String[] args) throws IOException
    {
      String name=null;
      double score=0, totalScore=0, count=0;    
      double avg=0;     
      
      File filename = new File("/C:/Documents and Settings/Sherry_Heart/Desktop/Data.txt"); 
      Scanner inputfile = new Scanner(filename);    
       
      while (inputfile.hasNext())   {       
          name = inputfile.next();      
          score = inputfile.nextDouble();
        
          while (score != -1)       { 
          System.out.print(name + " " + score + " ");  
              totalScore = totalScore + score;          
              score = inputfile.nextDouble();           
              System.out.print(score + " "); 
              count++;
              //count = count + 1;            
              avg = totalScore/count;  
              System.out.print("Players average: " + avg);        
              System.out.println(" ");
            }
    
        } 
    }
}



Edited by macosxnerd101: Please, :code:.

Is This A Good Question/Topic? 0
  • +

Replies To: Java Calculate Average using a Loop

#2 Luckless  Icon User is offline

  • </luck>
  • member icon

Reputation: 293
  • View blog
  • Posts: 1,146
  • Joined: 31-August 09

Re: Java Calculate Average using a Loop

Posted 22 October 2010 - 08:05 AM

I'm not sure if I understand your problem. Is it that you aren't passing the previous sum of numbers? you need to think of a sort of counter. Maybe scan the doubles into an ArrayList (up to the -1), increment a counter for each double read (up to the -1), then calculate a single average. Am I understanding you right?
Was This Post Helpful? 0
  • +
  • -

#3 starlite  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 22-October 10

Re: Java Calculate Average using a Loop

Posted 22 October 2010 - 08:22 AM

Sorry, if I sound confusing. First time posting for help.

The problem ask to write a program to read information from the file, display the original information (one line for each player) along with the player's average score of the season, and announce who is the highest average-scoring player of the team.

The file I am using looks like this:
Smith 13 20 8 12 -1
Burch 21 18 16 -1
Winorburg 9 14 14 23 25 -1

ThereforeI need to calculate & include each player's average to each line per player

So something like this:
Smith 13 20 8 12 Average Score: 13.25
Burch 21 18 16 Average Score: 18.33
Winorburg
Was This Post Helpful? 0
  • +
  • -

#4 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2876
  • View blog
  • Posts: 11,051
  • Joined: 15-July 08

Re: Java Calculate Average using a Loop

Posted 22 October 2010 - 08:59 AM

Move this out of the loop:
System.out.print("Players average: " + avg); 
System.out.println();


Was This Post Helpful? 0
  • +
  • -

#5 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Java Calculate Average using a Loop

Posted 22 October 2010 - 09:11 AM

You have most all the pieces. They need to be rearranged a bit. :)

You want to print the name either before the score accumulating loop or after it. I would suggest after the line that reads the name from the file.

Before the loop that reads the scores you need to initialize all the numeric variables back to zero so that the numbers reflect the current player and not all players.

Finally your average calculation and display lines should be after the score loop exits.
Was This Post Helpful? 0
  • +
  • -

#6 starlite  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 22-October 10

Re: Java Calculate Average using a Loop

Posted 22 October 2010 - 10:34 AM

Thanks everyone for your comments and assistance. This is what I have so far. I could use more help.

1. The least obvious problem is my first score is not showing up. The loop skips the first score but output the rest of the scores. How can I fix it so the loops starts at the first score?

2. The other problem I am having is the sentinel value -1 shows up in the output. How can I make it so it is not part of the output.

3. Now that I have taken the average calculation out of the loop processing I get it at the end of the output with an incorrect value. I was wondering can I use another while loop for this to display at the end of each player's score or should I consider using appending this data to the existing file using a while loop.

Any examples of code and Additional help would be greatly appreciated! Thanks in advance.


Program Output:
Smith
20.0
8.0
12.0
-1.0 //Like to make this disappear from each line of output
Burch
18.0
16.0
-1.0
Winorburg
14.0
14.0
23.0
25.0
-1.0
Player's average: 193.0 //Should be with each line for each player

 
import java.util.Scanner;
import java.io.*;

public class PlayerAverage
{
    public static void main(String[] args) throws IOException
    {
      String name=null; 
      double score=0, totalScore=0, count=0;    
      double avg=0;     
      
      File filename = new File("/C:/Documents and Settings/Sherry_Heart/Desktop/Data.txt"); 
      Scanner inputFile = new Scanner(filename); 

      while (inputFile.hasNext())   {       
          name = inputFile.next();    
          score = inputFile.nextDouble();
          System.out.println(name + " "); 
          System.out.print(" ");

          while (score != -1)       {   
          //System.out.print(name + " " + score + " ");    
               totalScore = totalScore + score;            
               score = inputFile.nextDouble(); 
               System.out.println(score + " " );
               System.out.print(" ");   
   
           }
        }
              count = count + 1;              
              avg = totalScore/count;     
              System.out.println("Player's average: " + avg);        
              System.out.print(" ");
              inputFile.close();
    } 
}


Was This Post Helpful? 0
  • +
  • -

#7 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10817
  • View blog
  • Posts: 40,326
  • Joined: 27-December 08

Re: Java Calculate Average using a Loop

Posted 22 October 2010 - 06:57 PM

Probably a good idea to print the current score first before reading in the next one. This should also handle not having the -1 printed.
          while (score != -1)       {   
          //System.out.print(name + " " + score + " ");    
               totalScore = totalScore + score;            
               score = inputFile.nextDouble(); 
               System.out.println(score + " " );
               System.out.print(" ");   
   
           }
        }
 }



As for your average, you only increment count by 1 outside of the loop, so you aren't getting an accurate tally of the quantity of scores you are reading in. You should probably increment count in the inner while loop to tally the quantity of scores for a Player, then reset it after the inner loop so the next Player doesn't start off with a tally of 5 scores when none have been read in.
Was This Post Helpful? 0
  • +
  • -

#8 starlite  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 22-October 10

Re: Java Calculate Average using a Loop

Posted 23 October 2010 - 12:22 PM

I got the first score in the loop. However, I am still stuggling with how to get the average for each player. What I am getting so far is one average at the end of the program. Do I need another loop? If so, can you provide some an example of how to do that? Any help would be appreciated.

Here is my code:

 import java.util.Scanner;
import java.io.*;

public class PlayerAverage
{
    public static void main(String[] args) throws IOException
    {
      String name; 
      double score=0, totalScore=0, count=0;    
      double avg=0;     
      
      File filename = new File("/C:/Documents and Settings/Sherry_Heart/Desktop/Data.txt"); 
      Scanner inputFile = new Scanner(filename); 

      while (inputFile.hasNext())   {       
          name = inputFile.next();    
          score = inputFile.nextDouble();
          System.out.println(name);
          System.out.println(score);
          
          while (score != -1)       {    
               totalScore = totalScore + score;            
               score = inputFile.nextDouble(); 
               count = count + 1;  
               System.out.println(score); 
            }
        }
              count = count + 1;             
              avg = totalScore/count;
              System.out.println("Player's average: " + avg);        
            
    }
    
} 


Here is my Output:
Smith
13.0
20.0
8.0
12.0
-1.0
Burch
21.0
18.0
16.0
-1.0
Winorburg
9.0
14.0
14.0
23.0
25.0
-1.0
Player's average: 14.846153846153847
Was This Post Helpful? 0
  • +
  • -

#9 starlite  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 22-October 10

Re: Java Calculate Average using a Loop

Posted 26 October 2010 - 07:33 PM

Hello Programmers alike,

I hope this is not a PM, I am new to the site and may not know my way around the site. I am in eager assistance. Here are the things I am having issues with my code:

1. How do I not output the -1 in the output, it is a sentinel value and does not need to display?
2. My average calculation is off, but not for the first average, only the ones after that, how do I correct that?
3. I need to display the highest average score, all I get is 0.0, how do I get the highest average score?

Any insight into any of these issues would be greatly appreciated. Sometimes explaining only in words, helps but an example is also very helpful.

Here is the code I hope I am doing this right

import java.util.Scanner;  
import java.io.*;  
 
public class PlayerAverage  

 {  
     public static void main(String[] args) throws IOException  
     {  

       String name = " ";   
       double score = 0;   
       double scoreSum = 0;  
       double avg = 0;  
       double newAvg = 0;  
       double highAvg = 0;  
       int count = 0;      

   
       File filename = new File("/C:/Documents and Settings/Sherry_Heart/Desktop/Data.txt");   
       Scanner inputFile = new Scanner(filename);   

       while (inputFile.hasNext())   {         
           name = inputFile.next();      
           score = inputFile.nextDouble();  
           System.out.println(name + " ");  
           System.out.println(score + " ");  
           
        while (score != -1)  {     
                scoreSum = scoreSum + score;              
                score = inputFile.nextDouble();   
                System.out.println(score + " ");   
                count = count + 1;  
             }  
               avg = (scoreSum)/count;  
               System.out.println("Player's average: " + avg);  

           if (avg > newAvg) {  
                newAvg = highAvg;  

            }  
              
         }  

             System.out.println("\nThe highest average score is: " + highAvg);  
             inputFile.close();  
     }  

 }  



Here is the output:

Smith
13.0
20.0
8.0
12.0
-1.0 //How do I not display? sentinel value (doesn't need to show)
Player's average: 13.25 //this average is correct
Burch
21.0
18.0
16.0
-1.0
Player's average: 15.428571428571429 //this average is not correct
Winorburg
9.0
14.0
14.0
23.0
25.0
-1.0
Player's average: 16.083333333333332 //this average is not correct

The highest average score is: 0.0 //empty variable

Thanks for your help in advance!!!
Was This Post Helpful? 0
  • +
  • -

#10 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8347
  • View blog
  • Posts: 31,913
  • Joined: 06-March 08

Re: Java Calculate Average using a Loop

Posted 26 October 2010 - 07:45 PM

The computation of the average should be done OUTSIDE the while loop for -1
Also never a good idea to check a double with equality

   while(score > 0) {
     .. display score
     .. add to total
     .. count number of score
     .. read next score
   }
   .. compute and display average


Was This Post Helpful? 0
  • +
  • -

#11 starlite  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 22-October 10

Re: Java Calculate Average using a Loop

Posted 27 October 2010 - 03:53 PM

Here is what I have. I am trying to solve two issues:

1. Calculating each player's average
2. Displaying the highest average score

I feel I am close I just don't know what else to do. Do you have suggestions? Thanks in advance :)

Here is my output:

Smith 13.0 20.0 8.0 12.0 Player's average: 0.0
Burch 21.0 18.0 16.0 Player's average: 0.0
Winorburg 9.0 14.0 14.0 23.0 25.0 Player's average: 0.0
Jones Player's average: 0.0

The highest average score is: 0.0

Here is my code
 import java.util.Scanner;
import java.io.*;

public class PlayerAverage
{
    public static void main(String[] args) throws IOException
    {
      String name = " "; 
      double score = 0; 
      double scoreSum;
      double avg;
      double highAvg = 0;
      int count;    

      File filename = new File("/C:/Documents and Settings/Sherry_Heart/Desktop/Data.txt"); 
      Scanner inputFile = new Scanner(filename); 
      
      while (inputFile.hasNext())   {       
          name = inputFile.next();    
          score = inputFile.nextDouble();
          System.out.print(name + " ");
                 
          while (score != -1)  {   
               System.out.print(score + " ");
               scoreSum = 0;
               count = 0;
               scoreSum = scoreSum + score;
               count = count + 1;
               score = inputFile.nextDouble(); 
            }
              scoreSum = 0;
              count = 0;
              avg = 0;
          if (count > 0) {
              avg = scoreSum/count; }
              
              System.out.println("Player's average: " + avg);
            }
        
              avg = 0;
          if (avg > highAvg) {
              avg = highAvg; }
              
            System.out.println("\nThe highest average score is: " + highAvg);
           
            inputFile.close();
    }
}


Was This Post Helpful? 0
  • +
  • -

#12 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10817
  • View blog
  • Posts: 40,326
  • Joined: 27-December 08

Re: Java Calculate Average using a Loop

Posted 27 October 2010 - 04:21 PM

Look at this section. You reset scoreSum and count before calculating the average, hence why it is 0.
scoreSum = 0;  
count = 0;  
avg = 0;  
if (count > 0) {  
       avg = scoreSum/count; }  



As for a findmax algorithm, you can work that into your get input section. Basically, you use a variable to hold the max value. Initialize it to Integer.MIN_VALUE (or whatever type you are using), as every value input will be higher than the min. So when you get a value in input, if it is greater than the current max, assign it to the max variable.

Look at this section. You reset scoreSum and count before calculating the average, hence why it is 0.
scoreSum = 0;  
count = 0;  
avg = 0;  
if (count > 0) {  
       avg = scoreSum/count; }  



As for a findmax algorithm, you can work that into your get input section. Basically, you use a variable to hold the max value. Initialize it to Integer.MIN_VALUE (or whatever type you are using), as every value input will be higher than the min. So when you get a value in input, if it is greater than the current max, assign it to the max variable.
Was This Post Helpful? 0
  • +
  • -

#13 starlite  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 22-October 10

Re: Java Calculate Average using a Loop

Posted 27 October 2010 - 05:04 PM

When I remove the reset code before the if statement I get an syntax error "count is not initialized".
I do not know what to do next, I have tried everything I am not getting how to get the average from the loop in a if statement. Can you explain with an example, that sometimes can be helpful as well. Thanks.
[code]
scoreSum = 0;
count = 0;
avg = 0;
if (count > 0) {
avg = scoreSum/count; }
Was This Post Helpful? 0
  • +
  • -

#14 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10817
  • View blog
  • Posts: 40,326
  • Joined: 27-December 08

Re: Java Calculate Average using a Loop

Posted 27 October 2010 - 05:16 PM

Initializing a variable simply assigning it an inital value. It is good practice to do this in order to avoid problems like you are experiencing currently.
Was This Post Helpful? 0
  • +
  • -

#15 starlite  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 22-October 10

Re: Java Calculate Average using a Loop

Posted 27 October 2010 - 06:00 PM

This is helping. However, it output the last score as the average now that my varibales are intialized. It shows the highest average score based on the results. What do you suggest to fix the this? Thanks a bunch :)

Here is output:

Smith 13.0 20.0 8.0 12.0 Player's average: 12.0
Burch 21.0 18.0 16.0 Player's average: 16.0
Winorburg 9.0 14.0 14.0 23.0 25.0 Player's average: 25.0
Jones Player's average: 25.0

The highest average score is: 25.0

Here is code:
 while (score != -1)  {   
               System.out.print(score + " ");
               totalScore = 0;
               count = 0;
               totalScore = totalScore + score;
               count = count + 1;
               score = inputFile.nextDouble(); 
            }    
          
            if (count > 0) {
              avg = totalScore/count; }
              System.out.println("Player's average: " + avg);
            
        }         
          if (avg > highAvg) {
              highAvg = avg; 
            }   
            System.out.println("\nThe highest average score is: " + highAvg);
        
            inputFile.close();
    }
   } 

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2