?
Solved

Help with code

Posted on 2011-10-02
18
Medium Priority
?
307 Views
Last Modified: 2012-05-12
Problem
I want to be upfront this is homework assignment that I am struggling through this week (partly due to our first child being born a couple days ago). I have displayed code template (thanks to Idle_Mind for his assistance). Need to see if I am on the right track with my first method main(). I posted the details of the assignment again (originally found under another question) so it can be understood my desired outcome. I would greatly appreciate any help in understanding how to achieve the output. Thank you very much!

Details
I am trying to create a scoring system where the user will input names and scores of all players. The program will calculate the average score and display all the players who scored below average.  

Sample Output
Enter Player Name (Q to quit): Bob

Enter score for Bob: 3245

Enter Player Name (Q to quit): Sue

Enter score for Sue: 1098
Enter Player Name (Q to quit): Q

Name     Score

Bob        3245

Sue        1098
Average Score: 3944.75

Players who scored below average

Name     Score

Bob        3245
Sue        1098

Variables
My variables are:
 InputData( ): Requests the user to input the player names and scores from the user and stores them into the two arrays for an unknown number of players <= 100.  
DisplayPlayerData(): Displays each player's name and score.
CalculateAverageScore( ): Calculates the average score and returns it by value.  
DisplayBelowAverage( ): Displays the names and scores of players who scored below average.

Thank you very much in advance!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {

        static string[] playerNameAr = new string[100];
        static double[] scoreAr = new double[100];

        public static void Main(string[] args)
        {
            int numPlayers = InputData();
            int scoreCnt;
            string inValue;
            DisplayPlayerData(numPlayers);
            double averageScore = CalculateAverageScore(numPlayers);
            Console.WriteLine("\nAverage Score: {0:F}", averageScore);
            DisplayBelowAverage(numPlayers, averageScore);

            Console.WriteLine("Enter Score{0}: " + "(Press Q to exit)", scoreCnt + 1);
            inValue = Console.ReadLine();

        }

        public static int InputData()
        {
            // do while name isn't "Q", store name/score and increment counter
            // return the counter value

            While(inValue != "Q")
            {
                scoreAr[scoreCnt] = Convert.ToInt32(inValue);
                ++scoreCnt;
                Conscole.Write("Enter score {0}: " +  "(Q to exit)", scoreCnt + 1);
                inValue = Console.ReadLine();
            }
            Console.WriteLine("The number of scores: " + scoreCnt);
        }

        public static void DisplayPlayerData(int numPlayers)
        {
            // iterate over arrays up to "numPlayers" and output
        }

        public static double CalculateAverageScore(int numPlayers)
        {
            // iterate over array up to "numPlayers" and keep running total, return average


        }

        public static void DisplayBelowAverage(int numPlayers, double avg)
        {
            //iterate over array up to "numPlayers" and output those less than the average
        }

    }
}

Open in new window

0
Comment
Question by:Michael Reeve
  • 7
  • 7
  • 4
18 Comments
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 36900902
Why are you using arrays? Is it a requirement?

If not - I would use List class. It is a collection where you add a new element when needed. It is easy to get a number of elements. OK, Lists are just better :)

Did not understand what this code is doing:
            Console.WriteLine("Enter Score{0}: " + "(Press Q to exit)", scoreCnt + 1);
            inValue = Console.ReadLine();

I believe you are on the right track.

One more. Why are you using 'double' for scores? Why not 'int'?
0
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 1000 total points
ID: 36900939
This was from his last post: http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_27375777.html

    "It is a basic example of the use of arrays"

Also, in the requirements, it has a subtle clue that the array max size should be 100:

    "... and stores them into the two arrays for an unknown number of players <= 100."

A List would certainly remove that limitation.   =)
*But I think he's supposed to use arrays.

See if you can decipher this code and then extrapolate what needs to be done with the other methods:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static int ArrSize = 100;

        static int[] scoreAr;
        static string[] playerNameAr;
        
        public static void Main(string[] args)
        {
            scoreAr = new int[ArrSize];
            playerNameAr = new string[ArrSize];
           
            int numPlayers = InputData();
            if (numPlayers > 0)
            {
                DisplayPlayerData(numPlayers);
                double averageScore = CalculateAverageScore(numPlayers);
                Console.WriteLine("\nAverage Score: {0:F}", averageScore);
                DisplayBelowAverage(numPlayers, averageScore);
            }
            Console.Write("Press Enter to Quit");
            Console.ReadLine();
        }

        public static int InputData()
        {
            int score;
            bool validScore;
            string name = "";
            int numEntered = 0;
            while (name.ToUpper() != "Q" && numEntered < ArrSize)
            {
                Console.Write("Enter Player Name (Q to quit): ");
                name = Console.ReadLine();
                if (name.ToUpper() != "Q")
                {
                    playerNameAr[numEntered] = name;
                    validScore = false;
                    do
                    {
                        Console.Write("Enter score for " + name + ": ");
                        if (int.TryParse(Console.ReadLine(), out score))
                        {
                            validScore = true;
                            scoreAr[numEntered] = score;
                        }
                        else
                        {
                            Console.WriteLine("Invalid Score.  Please try again...");
                        }
                    } while (!validScore);
                    numEntered++;
                }
            } 
            return numEntered;
        }

        public static void DisplayPlayerData(int numPlayers)
        {
            Console.WriteLine("\nName\tScore");
            for (int i = 0; i < numPlayers; i++)
            {
                Console.WriteLine(playerNameAr[i] + "\t" + scoreAr[i]);
            }
        }

        public static double CalculateAverageScore(int numPlayers)
        {
            double average = 0f;

            // iterate over array up to "numPlayers" and keep running total, return average

            return average;
        }

        public static void DisplayBelowAverage(int numPlayers, double avg)
        {
            //iterate over array up to "numPlayers" and output those less than the average
        }

    }
}

Open in new window

0
 

Author Comment

by:Michael Reeve
ID: 36901043
anarki_jimbel, Yes, arrays are a requirement. Good catch, I should use a int instead of double for the score.

Thanks Idle_Mind, let me take a shot at the code.

0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:Michael Reeve
ID: 36901124
Here is what I came up with for CalculateAverageScore method, however it is returning 0 as the average. Any ideas? I am tackling DisplayBelowAverage method next. I need to pass in the returned value from CalculateAverageScore. Is my approach close? Thanks
public static double CalculateAverageScore(int numPlayers)
        {            
            // iterate over array up to "numPlayers" and keep running total, return average
            double average = 0f;
            int pointsScored = 0;
            int total = 0;

            foreach (int i in scoreAr)
                total += i;
            
            if (pointsScored > 0)
                average = total/pointsScored;    
            
            return average;
        }

Open in new window

0
 

Author Comment

by:Michael Reeve
ID: 36901151
Here is the DisplayBelowAverage method, there seems to be many things wrong
1. Not passing in numPlayers from my array playerNameAr
2. No displaying the lowest average score

Again, any ideas where I am going wrong?
public static void DisplayBelowAverage(int numPlayers, double avg)
        {
            //iterate over array up to "numPlayers" and output those less than the average
            double playerAvg;

            Console.WriteLine();
            Console.Write("Player\t\tAvg Points");
            Console.Write("--------------------------");
            foreach (string s in playerNameAr)
            {
                playerAvg = numPlayers - avg;
                playerAvg = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("{0}\t", playerNameAr);
                Console.WriteLine("{0}", avg.ToString("FO"));
            }


        }

Open in new window

0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 36901177
See, you never set pointsScored. It is ALWAYS 0.

And as I understand all points are in your 'total' variable. To find average you need to divide total by number of players? Am I right?
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 36901202
For CalculateAverageScore(), we are passing in the number of players into the "numPlayers" variable.

So you can just use it to calculate your average...but you need to cast to doubles first:

                average = (double)total/(double)numPlayers;
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 36901206
Concerning showing players with less than average score.

 Think about algorithm.
- need to know number of players
- need to calculate average
Now we know average for all players. One player has NO average, he has just a score recorded in the array.

Therefore you run a loop for number of players and compare average and a score. If score is less - show the player's name.

Pseudo code is like:


for counter 0  to numPlayers -1

 if scoreAr(counter) < average than
     Print playerNameAr("This player below avrg: " + counter)
 end if

end loop

Open in new window

0
 

Author Comment

by:Michael Reeve
ID: 36901208
Yes, you are correct. I think I need to pass in numEntered from InputData method in order to find the average score in CalculateAverageScore method. Not sure though
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 36901210
For DisplayBelowAverage(), there shouldn't be any user input.

Use the variables passed in: "numPlayers" and "avg"

    public static void DisplayBelowAverage(int numPlayers, double avg)

Take a look at the loop I gave you in DisplayPlayerData().  

Your DisplayBelowAverage() method will be almost exactly the same except that you need to add a check inside the for loop to see if the current score is less than the passed in "avg" value.
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 36901212
Sorri - small mistake in pseudo :)
for counter 0  to numPlayers -1

 if scoreAr(counter) < average than
     Print ("This player below avrg: " + playerNameAr(counter))
 end if

end loop

Open in new window

0
 

Author Comment

by:Michael Reeve
ID: 36901265
What is my variable for my current score? I need to pass in my numEntered from InputData method and compare it to the avg. However, I don't understand why I am passing in avg when I should pass in average from CalculateAverageScore then compare it to the current score...just not sure where the current score is coming from (what variable)
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 36901331
Please take a close look at the DisplayPlayerData() method I posted back here:
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_27376303.html#36900939

It is using an indexed for loop to access both arrays.  So the "i" variable from the for loop is being used to access the "current" score and name from the arrays.

At line #26, I am passing in the number of players entered and the average score that was previously computed using CalculateAverageScore():  *the code isn't there yet as you are filling it in*

                DisplayBelowAverage(numPlayers, averageScore);

We need to pass in "numPlayers" because you simply can't iterate over the entire array.  Why not?...because the default value for entries in the array, even if we haven't used those slots, will be 0 (zero).  Thus, if you compare it to the average, zero will be less than it and you'll attempt to output a blank name and a zero score for a slot that wasn't actually assigned anything.
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 36901349
I believe the Main method is implemented by Idle Mind. I.e., you know what methods and in what order and with what arguments you need to invoke. So, what are your doubts?
0
 

Author Comment

by:Michael Reeve
ID: 36901528
I need to compare avg to the array scores then output it to a variable called averageScore which is used by the main method in the DisplayBelowAverage found in DisplayPlayerData

public static double DisplayBelowAverage(int numPlayers, double avg)
        {
            //iterate over array up to "numPlayers" and output those less than the average
            //need to compare the current score with the average score passed in
            double averageScore;
           
            Console.WriteLine("\nName\tScore");
            for (int i = 0; i < numPlayers; i++)
            {
                Console.WriteLine(playerNameAr[i] + "\t" + scoreAr[i]);
                averageScore = scoreAr/avg; //divide array by avg and place into a variable to be used above in main method
            }

        }

Open in new window

0
 
LVL 30

Assisted Solution

by:anarki_jimbel
anarki_jimbel earned 1000 total points
ID: 36906430
...then output it to a variable called averageScore"

What this value (variavle) represents?!

In the loop you have forgotten to check if scoreAr[i) less than average. I.e. you are outputting ALL players and scores. But you need to output only those who are below average. Put the line
Console.WriteLine(playerNameAr(i) + "\t" + scoreAr(i));
into an IF statement

The line
averageScore = scoreAr/avg;
does not make sense for me. Anyway it will produce an error. You cannot divide array by a number.
You don't need this line

I dont think you need to return anything from the DisplayBelowAverage method. Make it void. See also the Main method from Idle_Mind - no any value is returned. It does not make any sense.

public static void DisplayBelowAverage
0
 

Author Closing Comment

by:Michael Reeve
ID: 36907137
Sorry for the late response, just got home from work. Thank you both so much for your assistance and patience in working with me on my problem. I really appreciate your guidance as I worked through the problem. Once again, thank you for staying with me until the problem was resolved, despite a million questions. I was finally able to make it work (yes, it took a long time-ha!)
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 36907766
Good luck! :)
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses

755 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question