I am trying to create a mastermind game without using arrays that generates 5 random numbers 1-9, and you have 15 tries to guess them.*=Correct -=WRONG +=incorrect positionbut the number is right.
I created the first part of it, and it works for trying to guess the first random digit of 1-9. I am unsure of how to goto the second number for the player to guess the second 1-9 digit, and how to make the code keep using the same int's/keep adding onto the guesses that I set up already. I tried everyway I knew how and I can't figure it out. If I could get some assistance of where I am going wrong, and how to set it up correctly it would be very much appreciated. Cheers
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Decisions
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Guess the 5 Digit code, Under 15 tries!");
Random myRandom = new Random();
Int32 one = myRandom.Next(1, 10);
Int32 two = myRandom.Next(1, 10);
Int32 three = myRandom.Next(1, 10);
Int32 four = myRandom.Next(1, 10);
Int32 five = myRandom.Next(1, 10);
int guesses = 0;
bool incorrect = true;
do
{
if (guesses < 15)
Console.WriteLine("Guess a number between 1 and 9");
string result = Console.ReadLine();
guesses++;
if (guesses > 15)
Console.WriteLine("You went over 15 tries! Better luck next time");
if (result == one.ToString())
incorrect = false;
else if (result == two.ToString())
Console.WriteLine("+");
else if (result == three.ToString())
Console.WriteLine("+");
else if (result == four.ToString())
Console.WriteLine("+");
else if (result == five.ToString())
Console.WriteLine("+");
else
Console.WriteLine("-");
} while (incorrect);
if (guesses < 15)
Console.WriteLine("*Correct! It took {0} guesses.", guesses);
if (guesses > 15)
Console.WriteLine("You took to many tries! Better luck next time! Total Guesses: {0}", guesses);
Console.ReadLine();
}
}
}
I think what you're looking to use is a list. But first -
Keep in mind you want to be careful about how you order things in your program, especially when it comes to user experience. For instance:
if (guesses < 15)
Console.WriteLine("Guess a number between 1 and 9");
string result = Console.ReadLine();
guesses++;
if (guesses > 15)
Console.WriteLine("You went over 15 tries! Better luck next time");
So, when guesses is 14, it will show the text, have the user guess and increment "guesses" - however, when it iterates back to the beginning, your program will skip over the prompt: "Guess a number between 1 and 9" - but it will still wait for the users input. After they put in their input it will prompt that they went over the amount of tries, but it will still check if that number matched! How you order your program can be very important to a users experience.
Your program can look something like this:
const int iMaxGuesses = 15;
const int iListSize = 5;
static void Main(string[] args)
{
Random myRandom = new Random();
// Hold a list of integers
List<int> numbers = new List<int>();
int guesses = 0;
// Value where we will rebuild the code
string result = string.Empty;
// Placeholder for user's guess
string strGuess;
// Converted guess
int guess;
// Generate random list of numbers
for (int i = 0; i < iListSize; i++)
numbers.Add(myRandom.Next(1, 10));
// Prompt user
Console.WriteLine("Guess the {0} Digit code, Under {1} tries!", iListSize, iMaxGuesses);
// Open the game loop
do
{
// Check if we have exceeded the max amount of times we get to guess
if (guesses > iMaxGuesses)
Console.WriteLine("You went over 15 tries! Better luck next time");
else
{
// Prompt user
Console.WriteLine("Guess a number between 1 and 9");
// Get input
strGuess = Console.ReadLine();
// Check if input is in fact an integer, if so - put the value in our variable 'guess'
if (int.TryParse(strGuess, out guess))
{
// We have a proper guess, increment
guesses++;
// Checks if the number is the next in our list
if (numbers[0] == guess)
{
Console.WriteLine("Congratulations, {0} was a match!", guess);
// Remove that from the List
numbers.Remove(numbers[0]);
// Add it to our sequence (result)
result += guess;
}
else if(numbers.Contains(guess))
Console.WriteLine("Right number, wrong spot!");
else
Console.WriteLine("Incorrect, please try again!");
}
else // Inform user we will only accept numbered input
Console.WriteLine("That was not a number. Please try again!");
}
} while (guesses <= iMaxGuesses && numbers.Count > 0);
if (guesses < iMaxGuesses)
Console.WriteLine("Correct! It took {0} guesses to come up with the pattern {1}", guesses, result);
else
Console.WriteLine("You took to many tries! Better luck next time! Total Guesses: {0}", guesses);
Console.ReadLine();
}
Couple things to note: We have class-level constants for the List Size (we'll get to that) and how many guesses, in case these need to be changed on the fly. You can ignore this.
The first thing you may notice is a List of integers List<int> numbers = new List<int>() Here is some Reading (what is difference between string array and list of string in c#) about the differences between Arrays and Lists (collections).
We initialize the list of Random numbers by creating a loop the max size of our list, and ADDING a random integer to that list.
On the Do/While loop, we are checking that we are still less than iMaxGuesses and we have objects left in our list. So we take the users input. First we use int.TryParseto determine if we do actually have a number. If we do have a number, we will check that against the first number that appears in the list, numbers[0], and if it does, we remove it from the list: numbers.Remove(numbers[0]); The cool part about lists, is that when you REMOVE an item, it resizes the list, unlike an array that has a fixed size. So if your list is 12345, and you remove the 1, the next time you check the value of numbers[0], it will be 2!
I'm pretty sure the rest should be self explanatory. Let me know if anything was missed or you need help understanding anything.
Related
Hello I am trying to figure out why my program is not working, it's supposed to output a program in which department codes would be entered and followed by a prompt to enter a mark and so on until Q is entered. I can't seem to get that part working at all. If anyone could help please I will appreciate it.
// declare variables
char deptCode = ' ';
int count = 0;
double markVal, sum = 0, average = 0.0;
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
while (char.ToUpper(deptCode) != 'Q')
do
{
Console.Write("Enter a mark between 0 and 100 => ");
markVal = Convert.ToDouble(Console.ReadLine());
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
} while (markVal >= 0 && markVal <= 100);
count++;
average = (double)sum / count;
Console.WriteLine("***Error, Please Enter Valid Mark");
Console.WriteLine("The Average mark for Computer Science Students is {0}", average);
Console.WriteLine("The Average mark for Biology Students is {0}", average);
Console.WriteLine("The Average mark for Physics Students is {0}", average);
Console.ReadLine();
{
I am sympathetic to your dilemma and know it can be challenging to learn coding when you are not familiar with it. So hopefully the suggestions below may help to get you started at least down the right path. At the bottom of this is a basic “shell” but parts are missing and hopefully you will be able to fill in the missing parts.
One idea that you will find very helpful is if you break things down into pieces (methods) that will make things easier to follow and manage. In this particular case, you need to get a handle on the endless loops that you will be creating. From what I can see there would be three (3) possible endless loops that you will need to manage.
An endless loop that lets the user enter any number of discipline marks.
An endless loop when we ask the user which discipline to use
And an endless loop when we ask the user for a Mark between 0 and 100
When I say endless loop I mean that when we ask the user for a Discipline or a Mark… then, the user MUST press the “c”, “b” “p” or “q” character to exit the discipline loop. In addition the user MUST enter a valid double value between 0 and 100 to exit the Mark loop. The first endless loop will run allowing the user to enter multiple disciplines and marks and will not exit until the user presses the q character when selecting a discipline.
And finally when the user presses the ‘q’ character, then we can output the averages.
So to help… I will create two methods for you. One that will represent the endless loop for getting the Mark from the user… i.e.…. a number between 0 and 100. Then a second endless loop method that will get the Discipline from the user… i.e. … ‘c’, ‘b’, ‘p’ or ‘q’… and it may look something like…
private static char GetDisciplineFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a department code: ‘C’ for Computer Science,‘B’ for Biology, ‘P’ for Physics, or enter ‘Q’ to quit:");
userInput = Console.ReadLine().ToLower();
if (userInput.Length > 0) {
if (userInput[0] == 'c' || userInput[0] == 'b' ||
userInput[0] == 'p' || userInput[0] == 'q') {
return userInput[0];
}
}
Console.WriteLine("Invalid discipline => " + userInput + " try again.");
}
}
Note… the loop will never end until the user selects the characters ‘c’, ‘b’, ‘p’ or ‘q’. We can guarantee that when we call the method above, ONLY those characters are returned.
Next is the endless loop to get the Mark from the user and may look something like…
private static double GetMarkFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a mark between 0 and 100 => ");
userInput = Console.ReadLine().Trim();
if (double.TryParse(userInput, out double mark)) {
if (mark >= 0 && mark <= 100) {
return mark;
}
}
Console.WriteLine("Invalid Mark => " + userInput + " try again.");
}
}
Similar to the previous method, and one difference is we want to make sure that the user enters a valid number between 0 and 100. This is done using a TryParse method and most numeric types have a TryParse method and I highly recommend you get familiar with it when checking for valid numeric input.
These two methods should come in handy and simplify the main code. So your next issue which I will leave to you, is how are you going to store these values? When the user enters a CS 89 mark… how are you going to store this info? In this simple case… six variables may work like…
int totalsCSMarks = 0;
int totalsBiologyMarks = 0;
int totalsPhysicsMarks = 0;
double totalOfAllCSMarks = 0;
double totalOfAllBiologyMarks = 0;
double totalOfAllPhysicsMarks = 0;
Now you have something to store the users input in.
And finally the shell that would work using the methods above and you should see this uncomplicates things a bit in comparison to your current code. Hopefully you should be able to fill in the missing parts. Good Luck.
static void Main(string[] args) {
// you will need some kind of storage for each discipline.. see above...
char currentDiscipline = 'x';
double currentMark;
while (currentDiscipline != 'q') {
currentDiscipline = GetDisciplineFromUser();
if (currentDiscipline != 'q') {
currentMark = GetMarkFromUser();
switch (currentDiscipline) {
case 'c':
// add 1 to total number of CS marks
// add currentMarkValue to the total of CS marks
break;
case 'b':
// add 1 to total number of Biology marks
// add currentMarkValue to the total of Biology marks
break;
default: // <- we know for sure that only p could be left
// add 1 to total number of Physics marks
// add currentMarkValue to the total of Physics marks
break;
}
}
}
Console.WriteLine("Averages ------");
//Console.WriteLine("The Average mark for Computer Science Students is {0}", totalOfAllCSMarks / totalCSMarks);
//Console.WriteLine("The Average mark for Biology Students is {0}", ...);
//Console.WriteLine("The Average mark for Physics Students is {0}", ...);
Console.ReadLine();
}
I am in my second week of C# training, so I am pretty new to programming. I have to make a program that returns the smallest integer out of a series of random integer inputs. Once the input = 0, the program should break out of the loop. I am only allowed to use while and for loops. For some reason my program breaks out of loop after the second input and it looks like it doesn't even care if there is a "0" or not. Could you please see where I went wrong? I have been busting my head off with this. Sorry if this question has already been posted by somebody else but I did not find an answer to it anywhere.
PS: The zero input should be taken into account for the comparison.
So this is what I've got so far:
class Program
{
static void Main()
{
int i = 0;
int input = Int32.Parse(Console.ReadLine());
int min = default;
while (input != 0)
{
Console.ReadLine();
if (i == 0)
{
min = input;
break;
}
if (input < min && i !=0)
{
input = Convert.ToInt32(Console.ReadLine());
min = input;
}
i++;
}
Console.WriteLine(min);
}
First of all you will want to re-read the documentation for for- and while-loops. There are several useful pages out there.. e.g. for / while.
Problem
The reason why your loop breaks is that you initialize i with 0.
int i = 0;
Inside your loop you are using the if-statment to break the loop if the condition "i is 0" is met.
if (i == 0)
{
min = input;
break;
}
The input that the user has to provide each iteration of the loop is ignored by your program as you are never storing this kind of information to any variable.
while (input != 0)
{
Console.ReadLine();
// ...
}
Possible Solution
As a beginner it is helpful to tackle tasks step by step. Try to write down each of this steps to define a simple algorithm. As there are many solutions to this problem one possible way could be:
Declare minimum value + assign max value to it
Use a while loop and loop till a specific condition is matched
Read user-input and try converting it to an integer
Check whether the value is 0 or not
4.1. If the value is 0, go to step 8
4.2. If the value is not 0, go to step 5
Check whether the value is smaller than the current minimum value
5.1. If the value is smaller, go to step 6
5.2. If the value is not smaller, go back to step 3
Set the new minimum
Go back to step 3
Break the loop
End program
A program that handles the above steps could look like:
using System;
namespace FindMinimum
{
public class Program
{
static void Main(string[] args)
{
// Declare minimum value + assign initial value
int minValue = int.MaxValue;
// Loop until something else breaks out
while (true)
{
Console.WriteLine("Please insert any number...");
// Read io and try to parse it to int
bool parseOk = int.TryParse(Console.ReadLine(), out int num);
// If the user did not provide any number, let him retry
if (!parseOk)
{
Console.WriteLine("Incorrect input. Please insert numbers only.");
continue;
}
// If the user typed in a valid number and that number is zero, break out of the loop
if (parseOk && num == 0)
{
break;
}
// If the user typed in a valid number and that number is smaller than the minimum-value, set the new minimum
if (parseOk && num < minValue)
{
minValue = num;
}
}
// Print the result to the console
Console.WriteLine($"Minimum value: {minValue}.");
// Keep console open
Console.ReadLine();
}
}
}
Try This:
int input;
Console.Write("Enter number:");
input = Int32.Parse(Console.ReadLine());
int min = input;
while(true)
{
if (input == 0)
break;
if (min > input)
min = input;
Console.Write("Enter number:");
input = Int32.Parse(Console.ReadLine());
}
Console.WriteLine(min);
Console.ReadKey();
I hope it helps.
There was a test in school where we had to write a C# console program that reads positive integers below 100 from user input and then writes out some details like the biggest number. I used a list to store the numbers. I tested it with some random numbers I typed in but the program only adds the numbers to list starting with the second smallest one.
int count = 0;
List<int> bekertek = new List<int>();
int bekert = Convert.ToInt32(Console.ReadLine());
double atlag;
while (bekert > 0 && bekert < 100)
{
bekert = Convert.ToInt32(Console.ReadLine());
count++;
bekertek.Add(bekert);
}
/* This section is only for checking the list's elements
foreach (var i in bekertek)
{
Console.Write(i + " ");
}*/
Console.WriteLine("A bevitt adatok száma: {0}", count);
bekertek.Sort();
bekertek.Remove(bekertek.Last());
atlag = bekertek.Average();
Console.WriteLine("A legnagyobb érték: {0}", bekertek.Last());
Console.WriteLine("A legkisebb érték: {0}", bekertek.First());
Console.WriteLine("Az adatok átlaga: {0}", atlag);
What did I do wrong?
For input in console, I think the do...while loop is the ideal construct. Menus or requesting a number - it covers all of those.
As for what went wrong: Actually it adds all numbers to the collection (that debug code should confirm it). You just remove the smalest number from the collection between Sorting and Display:
bekertek.Sort();
bekertek.Remove(bekertek.Last()); //Should not have done this.
atlag = bekertek.Average();
There is a saying: "The 2 most common issues in Progamming is naming variables, chache invalidation and off-by-one errors." But this specific to make is somewhat unique :)
Edit: As Biesi Grr pointed out, you also ignore the first input:
int bekert = Convert.ToInt32(Console.ReadLine()); //this is never processed
double atlag;
while (bekert > 0 && bekert < 100)
{
bekert = Convert.ToInt32(Console.ReadLine());
count++;
bekertek.Add(bekert);
}
Maybe you wanted to use a ReadKey() here? There is also no need for a counter - that is actually the job of List.Lenght. In any case, a do..while would make that line unessesary any way.
let us make a fixed, do...while version
bool repeat= true;
do{
int bekert = Convert.ToInt32(Console.ReadLine());
if(bekert > 0 && bekert < 100)
bekertek.Add(bekert);
else
repeat = false;
}while(repeat )
I am creating a simple C# console application game that creates a random number, then displays either "too high", "too low" or "correct", it is then supposed to ask the user to input another number & then tell them whether that number is "too high", "too low" or "correct", once the right number is guessed, it should say "correct" and then display the number of guesses it took to get the correct number (this part I'm not sure how to do). Besides that I've created the code & it will tell you whether your guess is too high or too low, and once you try to enter a second guess it automatically says it's correct. How can I get the program to read more guesses, and how do I display the number of guesses?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _5.Number_Game
{
class Program
{
static void Main(string[] args)
{
double response, guess;
Random random = new Random();
int randomNumber = random.Next(1, 101);
do
{
Console.WriteLine("Enter your guess for a random number between 1 & 100");
guess = double.Parse(Console.ReadLine());
if (guess > randomNumber)
Console.WriteLine("Too high");
if (guess < randomNumber)
Console.WriteLine("Too low");
if (guess == randomNumber)
Console.WriteLine("Correct!");
Console.WriteLine("Enter another number");
response = double.Parse(Console.ReadLine());
}
while (response <= 1 && response >=100);
Console.WriteLine("Correct, Goodbye!");
Console.ReadLine();
}
}
}
Your "while" condition isn't right, it currently checks if the number is within the 1-100 range while it should check if it was the right number.
I would change it to:
while(guess != randomNumber);
or break when it is on the correct value:
if (guess == randomNumber)
{
Console.WriteLine("Correct!");
break;
}
I would also note that your "response" value is currently useless once you fix your algorithm.
You didn't need your guess as a double as the random number will only generate an integer. Also the responce variable is also not needed, as the loop can just be looped until:
while(guess != randomNumber);
Like the above answer said. If you would like to add a count of how many guesses the user takes to guess the number, add a count variable before the the opening 'do' loop.
int count = 0;
do
{
And in each guess where the user doesn't guess it correctly increment the count by one, just like this:
if (guess > randomNumber)
{
Console.WriteLine("Too high");
count += 1;
}
if (guess < randomNumber)
{
Console.WriteLine("Too low");
count += 1;
}
Then at the end when user guesses correctly
if (guess == randomNumber)
{
Console.WriteLine("Correct!");
Console.WriteLine("You took " + count + "guesses, to guess that number.");
}
I'm a fairly inexperienced programmer, and i'm currently working on a Console Application project. It's basically a little 'mathematics game'; the application generates two random numbers, that have either been added, subtracted, multiplied or divided against each other randomly. The answer is shown on screen and the user has to pick from the menu which is the right mathematical operator, once the correct answer is picked the application then displays on screen how long it took for the user in milliseconds to input the correct answer.
Now I want to save the times of the players in an array that can be called up later with all the scores. I need to include a method in this programme and I figured a method to save the times into an array would be suitable. I seem to have stumbled across a little problem though.
I'm not quite sure what's wrong:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Mathgame
{
class Program
{
}
class arrayclass
{
public static void saveInArray(int duration)
{
int[] TopTenScores = {000,1000,2000,3000,4000,5000,6000,7000,8000,9000};
if (duration < 1000)
{
duration = TopTenScores[000];
}
else if ((duration >= 1000) && (duration <= 1999))
{
duration = TopTenScores[1000];
}
else if ((duration >= 2000) && (duration <= 2999))
{
duration = TopTenScores[2000];
}
else if ((duration >= 3000) && (duration <= 3999))
{
duration = TopTenScores[3000];
}
else if ((duration >= 4000) && (duration <= 4999))
{
duration = TopTenScores[4000];
}
else if ((duration >= 5000) && (duration <= 5999))
{
duration = TopTenScores[5000];
}
else if ((duration >= 6000) && (duration <= 6999))
{
duration = TopTenScores[6000];
}
else if ((duration >= 7000) && (duration <= 7999))
{
duration = TopTenScores[7000];
}
else if ((duration >= 8000) && (duration <= 8999))
{
duration = TopTenScores[8000];
}
else if ((duration >= 9000) && (duration <= 9999))
{
duration = TopTenScores[9000];
}
Console.WriteLine(TopTenScores);
}
static void Main(string[] args)
{
int intInput, num1, num2, incorrect, array1;
float answer;
string input;
System.Random randNum = new System.Random();
Console.WriteLine("Welcome to the Maths game!");
Console.WriteLine("(Apologies for the glitchiness!)");
Console.WriteLine();
Console.WriteLine("Please choose from the following options:");
Console.WriteLine();
retry:
Console.WriteLine("1 - Test your Maths against the clock!");
Console.WriteLine("2 - Exit the application.");
Console.WriteLine("3 - Top scores");
Console.WriteLine();
input = Console.ReadLine();
intInput = int.Parse(input);
if (intInput == 1)
{
goto start;
}
else if (intInput == 2)
{
goto fin;
}
else if (intInput == 3)
{
array1 = array1.saveInArray;
goto retry;
}
Now, in the last 'else if' statement in the code, you can see my variable array1 trying to call the method, but no matter what I do I keep getting errors.
This is the only error I have at the moment, but I have a feeling soon as I resolve that error, another will come up. For now i'm just determined to get past this error:
'int' does not contain a definition for 'saveInArray' and no extension method 'saveInArray' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?).
Any help would be kindly appreciated, apologies in advanced for my ugly written code! And thank you to any help that I receive!
Regards,
Omar.
Okay,
There's quite a bit in this code that needs fixing TBH.
I'll start with your error first:
You are declaring the variable array1 as an integer. In C# integers are primitive types. This means that they have no methods and no class members. So, when you call array1.saveInArray the compiler is basically saying "the type integer doesn't have any methods... I can't find an appropriate method to match your call".
Instead of calling array1.saveInArray I think what you meant to call was arrayclass.saveInArray(x).
Notice the x in that call above. I'm passing a variable called x which is of type int into the function saveInArray().
This brings us to the second error. If saveInArray was a property, then you could just go arrayclass.saveInArray. However, it is a function which requires an argument... namely an integer.
When you call arrayclass.saveInArray(someInteger) you are passing someInteger as an argument into a method. The method is then free to use this argument to do its calculations.
That should fix your most basic errors and hopefully you can compile.
Moving on to some other errors that will cause you problems at runtime:
In the method saveInArray you are declaring an integer array called TopTenScores.
You are declaring this fine... however later on when you are indexing into TopTenScores, you are using an index that is way out of range of TopTenScores.
Here is your declaration of TopTenScores:
int[] TopTenScores = {000,1000,2000,3000,4000,5000,6000,7000,8000,9000};
Notice that there are 10 numbers in this declaration. This means that the max index you can have is 9. Why? Because arrays start indexing at 0 in C#.
I think you might be thinking that this array is associative... however this is not the case. When you do TopTenScores[1000] you are saying "give me the value at index 1000". This value does not exists and you will get a runtime error.
Instead, you would want to call TopTenScores[1] if you wanted to access the value 1000.
Also, you are not overwriting the default value with the new top score, rather you are overwriting the new top score with the default value. I don't think this is intended. Instead, switch your calls from this: duration = TopTenScores[1000];
to this: TopTenScores[1] = duration;
Edit: Lastly, as the commenter pointed out, using goto is bad practice and greatly discouraged. You will understand why later on as you start to understand program flow and organization better. For now, it is best to try and avoid the habit of using goto. goto maps to a low level system construct, which we should avoid when using a higher level language like C#. Your code can get confusing and error prone quickly with using goto.
Anyways, feel free to ask more questions/comment etc if you have questions or you need to clarify something. Welcome to StackOverflow!
One of your problems is that you're missing the fundamental concept of what an array is. Think of an array as a row of numbered mailboxes. This line of code:
int[] TopTenScores = {000,1000,2000,3000,4000,5000,6000,7000,8000,9000};
is creating an array of 10 integers that look something like this in memory:
Index Value
----- -----
0 0
1 1000
2 2000
3 3000
4 4000
5 5000
6 6000
7 7000
8 8000
9 9000
It is unclear how this is a useful structure to represent your top scores, and I'm not sure what your saveInArray method is trying to do. In that method, here's how one of your lines of code is interpreted:
duration = TopTenScores[1000];
What that means is "take what's at index 1000 of TopTenScores and store it in duration." As you can see from the table above, there is no index 1000, and besides, that code has nothing to do with saving a top score.
Another problem you're having is that you don't seem to have your algorithm in place for accomplishing the task. For the top ten functionality, try breaking down what needs to be done into instructions on how you would do it manually if you were a score keeper. It would be something like this:
I keep track of the top scores by stacking index cards with the scores on them in order of highest to lowest. At first, I have no index cards.
I can do two things: record scores and tell someone the top ten scores.
When someone asks me to record a score, I:
Write the score down on an index card
Look through the stack of previous scores in order until I find a score lower than this new score.
If I find a score that was lower than this new one, I place the card on top of the lower score.
Otherwise, if this score is the lowest one of the bunch, including if this is the first score recorded, I'll place the score at the bottom of the stack.
When someone asks me to tell them the top 10 scores, I:
Go through the first 10 cards or all the cards if I have less than 10.
For each of those scores, write them down in order.
Give the list of scores to the one requesting them.
It may seem silly to do this, but most programs are really only sequences of simple steps, and as a programmer, you need to be able to determine those steps before translating them into a language that the compiler can understand. Once you formulate the problem in simple terms, you can start translating it into code for example:
// You can think of a role a person would do for a manual process as a class
// in a program.
public class ScoreKeeper
{
// Our high score list (stack of cards) is empty to begin with. Unlike
// arrays, lists allow us insert items rather than placing them in
// numbered slots.
private List<int> _scores = new List<int>();
// This is the method for when someone asks us to record a score. The
// "score" parameter is the new score which you can think of as being
// written on a card.
public void RecordScore(int score)
{
// Go through each of the existing scores. "i" is the index in the
// list.
for (int i = 0; i < _scores.Count; i++)
{
// See if the new score is less than the score at index #i
if (_scores[i] < score)
{
// It is lower than this new score. Insert the new score
// above that score.
_scores.Insert(i, score);
// We're done. Stop looping and exit RecordScore.
return;
}
}
// If we get here, we found no scores lower than this new one. Add
// this score to the bottom of the stack.
_scores.Add(score);
}
// This is the method for when someone asks us for the top 10 scores.
// Notice that we return an array of integers, which will represent
// our piece of paper we hand back to the one requesting the scores.
public int[] GetTop10Scores()
{
// We start with a blank piece of paper.
int[] result = new int[10];
// Go through the scores. The first 10 are the top 10 because
// RecordScore puts them in order. We also need to make sure
// we don't try to get more scores than we've recorded.
for (int i = 0; i < 10 && i < _scores.Count; i++)
{
// Write down the score on the paper
result[i] = _scores[i];
}
// Send back the list of scores to the requester
return result;
}
}
Now, inside of your main program, you can create a ScoreKeeper and ask it to do its score keeping:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to the Maths game!");
Console.WriteLine("(Apologies for the glitchiness!)");
Console.WriteLine();
Console.WriteLine("Please choose from the following options:");
Console.WriteLine();
// This object keeps track of scores
ScoreKeeper scoreKeeper = new ScoreKeeper();
bool keepRunning = true;
while (keepRunning)
{
Console.WriteLine("1 - Test your Maths against the clock!");
Console.WriteLine("2 - Exit the application.");
Console.WriteLine("3 - Top scores");
Console.WriteLine();
string input = Console.ReadLine();
int intInput = int.Parse(input);
if (intInput == 1)
{
// You should avoid gotos. Try writing a method instead
// Play the game and get the player's score.
int newScore = PlayGame();
// Have the score keeper record the new score.
scoreKeeper.RecordScore(newScore);
}
else if (intInput == 2)
{
keepRunning = false;
}
else if (intInput == 3)
{
// Get the top scores from the score keeper
int[] topScores = scoreKeeper.GetTop10Scores();
// Print each score
for (int i = 0; i < topScores.Length; i++)
{
Console.WriteLine("{0}: {1}", i + 1, topScores[i]);
}
}
}
}
private static int PlayGame()
{
// Put your game logic in here. Return the score.
}
}
Once you become more familiar with the fundamentals of programming, you'll find there are existing classes you can reuse, like SortedList, that can already take care of common tasks like maintaining an ordered list.