I'm creating a lottery program that users can choose from a series of numbers between a particular range and the program then creates its own version of numbers and compares those user values against the program's random numbers which any matches that the program then finds are then displayed to the user.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assessment1.Lottery
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please insert 6 lottery numbers:");
int range = 100;
int minValue = 0;
int maxValue = 100;
int a = 0;
Random rnd = new Random();
int[] myArray = new int[6];
for ( int i=0; i < myArray.Length; i++ )
{
int randomNumber = rnd.Next(minValue, maxValue);
myArray[i] = randomNumber;
Console.WriteLine(randomNumber);
myArray[i] = int.Parse(Console.ReadLine());
Console.WriteLine(myArray[i]);
while (a < 5)
{
if (int.TryParse(Console.ReadLine(), out myArray[a]))
a++;
else
Console.WriteLine("invalid integer");
}
double arry = myArray.Average();
if(arry > 0)
Console.WriteLine("found");
else
Console.WriteLine("not found");
int BinarySearch(int[] array, int value, int low, int high)
{
if ( high >= low)
{
int mid = (low + high) / 2;
if (array[mid] == value) return mid;
if (array[mid] == value) return BinarySearch(array, value, low, mid - 1);
return BinarySearch(array, value, mid + 1, high);
}
return -1;
}
}
Console.ReadLine();
}
}
}
when I run the program it shows the following
Please insert 6 lottery numbers: 64
how can I fix this so that the array can be filled with user input
Here is a version of something I wrote a while back and modified to your parameters, if there are bugs please don't ask me to fix.
static void Main(string[] args)
{
int stop = 0;
int[] chosenNum = new int[6];
while (stop == 0)
{
Console.Clear();
string con = "";
Console.WriteLine("Enter six numbers between 1-100 separated by a comma with no duplicates:");
string numbers = Console.ReadLine();
string[] userNumbers = numbers.Replace(" ", "").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToArray();;//remove ex: ,, issues
string[] checkDup = userNumbers.Distinct().ToArray();//remove duplicates
if (userNumbers.Count() < 6)
{
Console.WriteLine("You entered less than six numbers");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (userNumbers.Count() > 6)
{
Console.WriteLine("You entered more than 6 numbers");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (checkDup.Count() < 6)
{
Console.WriteLine("You entered duplicate numbers");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (!isNumeric(userNumbers))
{
Console.WriteLine("You entered non-numeric value(s)");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else if (isInRange(userNumbers) < 6)
{
Console.WriteLine("You entered out of range value(s)");
Console.WriteLine("Try Again Y or N");
con = Console.ReadLine();
if (con.ToUpper() != "Y")
{
stop = 1;
}
}
else
{
var lowerBound = 1;
var upperBound = 100;
var random = new Random();
int[] randomNum = new int[6];
int count = 0;
foreach(string str in userNumbers){
var rNum = random.Next(lowerBound, upperBound);
randomNum[count] = rNum;
count++;
}
string[] ourPicks = Array.ConvertAll(randomNum, s => s.ToString()).ToArray();
Array.Sort(userNumbers);
Array.Sort(ourPicks);
//string[] ourpicks = { "1", "2" };//for testing
Console.WriteLine("Your Numbers: {0}", string.Join(", ", userNumbers));
Console.WriteLine("Our Numbers: {0}", string.Join(", ", ourPicks));
string[] result = userNumbers.Intersect(ourPicks).ToArray();
if(result.Count() > 0)
{
Console.WriteLine("Matchs: {0}", string.Join(", ", result));
}
else
{
Console.WriteLine("Match's = 0");
}
stop = 1;
}
}
Console.ReadLine();
}
public static bool isNumeric(string[] num)
{
foreach (string str in num)
{
bool check = int.TryParse(str, out int test);
if (!check)
{
return false;
}
}
return true;
}
public static int isInRange(string[] num)
{
int count = 0;
foreach (string str in num)
{
int.TryParse(str, out int test);
if (test > 0 & test <= 100)
{
count++;
}
}
return count;
}
Related
I am a Beginner in C# and I was wondering what I got wrong with this code.
I want the user to input the amount of numbers
Then an array with that amount gets created
Then finally I want to display all the numbers in the array.
The Code:
using System;
using System.Threading;
using System.Collections.Generic;
namespace Console_Project_alpha
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the amount of numbers: ");
int amount = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[amount];
string nth = "";
for( int i = 1; i <= amount ; i++)
{
if(i == 1)
{
nth = i + "st";
}
else if( i == 2)
{
nth = i + "nd";
}
else if( i == 3)
{
nth = i + "rd";
}else{
nth = i + "th";
}
Console.Write("\nEnter " + nth + " Number:");
int num = Convert.ToInt32(Console.ReadLine());
for(int j = 0; j <= numbers.Length; j++)
{
numbers[j] = num;
}
}
System.Console.WriteLine(numbers);
}
}
}
Any help is highly appreciated. Thanks in advance
In your code you all time overwriting the same value to all index in
array.
If you want to display values from array in console just iterate after array
Properly worked example based on your code:
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the amount of numbers: ");
int amount = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[amount];
string nth = "";
int index = 0;
for (int i = 1; i <= amount; i++)
{
if (i == 1)
{
nth = i + "st";
}
else if (i == 2)
{
nth = i + "nd";
}
else if (i == 3)
{
nth = i + "rd";
}
else
{
nth = i + "th";
}
Console.Write("\nEnter " + nth + " Number:");
int num = Convert.ToInt32(Console.ReadLine());
numbers[index] = num;
index++;
}
for (int i = 0; i <= numbers.Length - 1; i++)
{
Console.WriteLine(numbers[i]);
}
Console.ReadLine();
}
}
The following line of code is not working as expected: If there are two dictionary entries it prints "2, 2" instead of "1, 2"
Console.WriteLine($"Student: {studentMap.Count} - Average Score: {average} - Letter Grade: {GetLetterGrade(average)}");
It is not listing the dictionary count like this line ↓↓↓ of code above it in the other for-loop.
Console.WriteLine($"Enter test {studentScores.Count + 1 } for student {studentMap.Count + 1 }");
namespace Program
{
class Program
{
static void Main(string[] args)
{
string totalStudents = string.Empty;
while (!IsNumeric(totalStudents))
{
Console.WriteLine("How many students will you be grading?");
totalStudents = Console.ReadLine();
if (!IsNumeric(totalStudents))
{
Console.WriteLine(string.Empty);
Console.WriteLine("Error! Please enter numeric value.");
}
}
int studentCount = Convert.ToInt32(totalStudents);
Console.WriteLine(string.Empty);
string totalScores = string.Empty;
while (!IsNumeric(totalScores))
{
Console.WriteLine("How many test scores will you enter for each student?");
totalScores = Console.ReadLine();
if (!IsNumeric(totalScores))
Console.WriteLine("Please enter a numeric value.");
}
int scoreCount = Convert.ToInt32(totalScores);
Dictionary<int, List<int>> studentMap = new Dictionary<int, List<int>>();
for (int students = 0; students < studentCount; students++)
{
List<int> studentScores = new List<int>();
for (int scores = 0; scores < scoreCount; scores++)
{
string scoreInput = string.Empty;
Console.WriteLine(string.Empty);
Console.WriteLine($"Enter test {studentScores.Count + 1 } for student {studentMap.Count + 1 }");
scoreInput = Console.ReadLine();
Console.WriteLine(string.Empty);
Console.WriteLine("--------------------");
int intScore = Convert.ToInt32(scoreInput);
studentScores.Add(intScore);
}
studentMap.Add(students, studentScores);
}
Console.WriteLine("The test results are as follows:");
Console.WriteLine(string.Empty);
for (int i = 0; i < studentMap.Count; i++)
{
List<int> studentScores = studentMap[i];
double scoreSum = studentScores.Sum();
double scoreNum = studentScores.Count();
double average = scoreSum / scoreNum;
Console.WriteLine($"Student: {studentMap.Count} - Average Score: {average} - Letter Grade: {GetLetterGrade(average)}");
}
Console.WriteLine();
Console.ReadLine();
}
static string GetLetterGrade(double average)
{
if (average >= 90)
{
return "A";
}
else if (average >= 80)
{
return "B";
}
else if (average >= 70)
{
return "C";
}
else if (average >= 60)
{
return "D";
}
else
{
return "F";
}
}
static double GetAverage(double sum, double count)
{
return sum / count;
}
static bool IsNumeric(string input)
{
int result;
return int.TryParse(input, out result);
}
}
}
You probably misunderstood the terms Dictionary<>.Count and index. Indexes start at 0 and Count property represents the number of items in the dictionary.
So, if you have 1 item in your Dictionary<>, it's index is 0 and Dictionary<>.Count is 1.
I need to find the difference of each number value in an array from an average value. I need to loop through each value and subtract each value FROM the average and display the difference. I have tried several different ways but the difference always comes out as 0 at the end. What am i doing wrong here?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace AvgNDiff
{
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[10];
int x = 0;
int i;
string entryString = "";
int counter = 0;
int countdown = 10;
int sum = 0;
int average = 0;
while (counter < numbers.Length && numbers[x] != 10 && entryString != "0")
{
if (x == 0)
Write("Enter up to 10 numbers or type 0 to stop > ");
else if (x == 9)
Write("Enter {0} more number or type 0 to stop > ", countdown);
else
Write("Enter up to {0} more numbers or type 0 to stop > ", countdown);
entryString = ReadLine();
numbers[x] = Convert.ToInt32(entryString);
if (entryString != "0")
{
sum += numbers[x];
counter++;
x++;
}
countdown--;
}
average = sum / x;
WriteLine("\n\nYou entered {0} numbers with a sum of {1}", x, sum);
WriteLine("The average of your numbers is " + average);
WriteLine("\n\nNumber Difference");
WriteLine("-------------------------------");
for (i=0; i < x; i++)
{
int value = numbers[i];
int diff = average-value;
WriteLine(String.Format("{0,-10} {1,-10}", (numbers[i]), diff));
}
ReadKey();
}
}
}
Take a look here
int value = numbers[i];
int diff = value - average;
WriteLine(String.Format("{0,-10} {1,-10}", (numbers[i]), value));
the key issue here is the writeline statement.
Youve told it to display numbers[i], and oh wait.. numbers[i] (as thats what value is)
yet diff contains the variance from the average...
static void Main(string[] args)
{
List<int> numberList = new List<int>();
Console.WriteLine("Enter up to 10 numbers or type 0 to stop:");
for (int i = 0; i < 10; i++)
{
int userInput = 0;
while (!int.TryParse(Console.ReadLine(), out userInput))
{
Console.WriteLine("Only integer numbers accepted, let's try again...:");
}
if (userInput == 0)
{
break;
}
else
{
numberList.Add(userInput);
if (i < 9)
{
Console.WriteLine("Yeah, {0} more number{1} to go!", (9 - i), (i == 8 ? "" : "s"));
}
}
}
double average = numberList.Average();
for (int i = 0; i < numberList.Count; i++)
{
Console.WriteLine("#{0}: {1} - {2} = {3}", (i+1), numberList[i], average, (numberList[i] - average));
}
Console.ReadLine();
}
Do not cram the entire soultion into the single Main, extract (and debug) a method:
// Subtract each item from the average
private static double[] MyNormalize(int[] source) {
double sum = 0.0;
foreach (var item in source)
sum += item;
double[] result = new double[source.Length];
for (int i = 0; i < source.Length; ++i)
result[i] = sum / source.Length - source[i];
return result;
}
...
static void Main(string[] args) {
int[] numbers = new int[10];
...
// Input
while (counter < numbers.Length && numbers[x] != 10 && entryString != "0") {
...
entryString = ReadLine();
numbers[x] = Convert.ToInt32(entryString);
}
// Business logic
double[] norm = MyNormalize(numbers);
// Output
for (int i = 0; i < numbers.Length; ++i)
WriteLine(String.Format("{0,-10} {1,-10}", numbers[i], norm[i]));
}
I'm very new to c# and programming in general. I'm having some issues trying to get this program to work.
I've to input 5 names from a text file, add 5 scores to each name, remove the max and min score for each name, and then display the winner. What I have done so far only seems to be adding up all the scores. Could anyone point me in the right direction?
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Diving_Championship
{
class Program
{
static void Main(string[] args)
{
string[] divers = File.ReadAllLines(#"F:\1 -C# Programming\Coursework\DiverName.txt");
string DiverScore;
int score = 0;
int max = 0;
int min = 10;
int Totalscore = 0;
int[] Finalscore = new int[5];
int max1 = 0;
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < 5; i++)
{
DiverScore = divers[i];
Console.WriteLine("Please Enter a Score between 0 and 10 for {0}", DiverScore);
score = Convert.ToInt16(Console.ReadLine());
while (score < 0 || score > 10)
{
Console.WriteLine("Score Is Invalid, Please Re-Enter a score between 0 and 10");
score = Convert.ToInt16(Console.ReadLine());
}
if (score > max)
{
max = score;
}
if (score < min)
{
min = score;
}
Totalscore += score;
}
}
for (int i = 0; i < 5; i++)
{
Finalscore[i] = Totalscore - max - min;
if (Finalscore[0] > max1)
{
max1 = Finalscore[0];
}
if (Finalscore[1] > max1)
{
max1 = Finalscore[1];
}
if (Finalscore[2] > max1)
{
max1 = Finalscore[2];
}
if (Finalscore[3] > max1)
{
max1 = Finalscore[3];
}
if (Finalscore[4] > max1)
{
max1 = Finalscore[4];
}
}
Console.WriteLine("the max score is {0}", max1);
}
}
}
Looks like i was completely barking up the wrong tree, i have finally got my code to work, but thanks for all your input. It's not the prettiest code but it works :P
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DivingChampionship_Coursework
{
class Program
{
static void Main(string[] args)
{
string[] divers = File.ReadAllLines(#"F:\1 -C# Programming\Coursework\DiverName.txt");
int score1 = 0;
int score2 = 0;
int score3 = 0;
int score4 = 0;
int score5 = 0;
Diver1(ref divers, ref score1);
Diver2(ref divers, ref score2);
Diver3(ref divers, ref score3);
Diver4(ref divers, ref score4);
Diver5(ref divers, ref score5);
FindWinner(ref divers, ref score1, ref score2, ref score3, ref score4, ref score5);
}
static void Diver1(ref string[] divers, ref int score1)
{
int[] diver1 = new int[5];
int max1 = 0;
int min1 = 10;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please Enter a score for {0}", divers[0]);
diver1[i] = Convert.ToInt16(Console.ReadLine());
while (diver1[i] < 0 || diver1[i] > 10)
{
Console.WriteLine("Opps, the score you have entered is incorrect, please enter valid score");
diver1[i] = Convert.ToInt16(Console.ReadLine());
}
if (diver1[i] < min1)
{
min1 = diver1[i];
}
if (diver1[i] > max1)
{
max1 = diver1[i];
}
}
score1 = diver1[0] + diver1[1] + diver1[2] + diver1[3] + diver1[4] - max1 - min1;
Console.WriteLine("Total score is {0} from {1}", score1, divers[0]);
Console.WriteLine();
}
static void Diver2(ref string[] divers, ref int score2)
{
int[] diver2 = new int[5];
int max2 = 0;
int min2 = 10;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please Enter a score for {0}", divers[1]);
diver2[i] = Convert.ToInt16(Console.ReadLine());
while (diver2[i] < 0 || diver2[i] > 10)
{
Console.WriteLine("Opps, the score you have entered is incorrect, please enter valid score");
diver2[i] = Convert.ToInt16(Console.ReadLine());
}
if (diver2[i] < min2)
{
min2 = diver2[i];
}
if (diver2[i] > max2)
{
max2 = diver2[i];
}
}
score2 = diver2[0] + diver2[1] + diver2[2] + diver2[3] + diver2[4] - max2 - min2;
Console.WriteLine("Total score is {0} from {1}", score2, divers[1]);
Console.WriteLine();
}
static void Diver3(ref string[] divers, ref int score3)
{
int[] diver3 = new int[5];
int max3 = 0;
int min3 = 10;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please Enter a score for {0}", divers[2]);
diver3[i] = Convert.ToInt16(Console.ReadLine());
while (diver3[i] < 0 || diver3[i] > 10)
{
Console.WriteLine("Opps, the score you have entered is incorrect, please enter valid score");
diver3[i] = Convert.ToInt16(Console.ReadLine());
}
if (diver3[i] < min3)
{
min3 = diver3[i];
}
if (diver3[i] > max3)
{
max3 = diver3[i];
}
}
score3 = diver3[0] + diver3[1] + diver3[2] + diver3[3] + diver3[4] - max3 - min3;
Console.WriteLine("Total score is {0} from {1}", score3, divers[2]);
Console.WriteLine();
}
static void Diver4(ref string[] divers, ref int score4)
{
int[] diver4 = new int[5];
int max4 = 0;
int min4 = 10;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please Enter a score for {0}", divers[3]);
diver4[i] = Convert.ToInt16(Console.ReadLine());
while (diver4[i] < 0 || diver4[i] > 10)
{
Console.WriteLine("Opps, the score you have entered is incorrect, please enter valid score");
diver4[i] = Convert.ToInt16(Console.ReadLine());
}
if (diver4[i] < min4)
{
min4 = diver4[i];
}
if (diver4[i] > max4)
{
max4 = diver4[i];
}
}
score4 = diver4[0] + diver4[1] + diver4[2] + diver4[3] + diver4[4] - max4 - min4;
Console.WriteLine("Total score is {0} from {1}", score4, divers[3]);
Console.WriteLine();
}
static void Diver5(ref string[] divers, ref int score5)
{
int[] diver5 = new int[5];
int max5 = 0;
int min5 = 10;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Please Enter a score for {0}", divers[4]);
diver5[i] = Convert.ToInt16(Console.ReadLine());
while (diver5[i] < 0 || diver5[i] > 10)
{
Console.WriteLine("Opps, the score you have entered is incorrect, please enter valid score");
diver5[i] = Convert.ToInt16(Console.ReadLine());
}
if (diver5[i] < min5)
{
min5 = diver5[i];
}
if (diver5[i] > max5)
{
max5 = diver5[i];
}
}
score5 = diver5[0] + diver5[1] + diver5[2] + diver5[3] + diver5[4] - max5 - min5;
Console.WriteLine("Total score is {0} from {1}", score5, divers[4]);
Console.WriteLine();
}
static void FindWinner(ref string[] divers, ref int score1, ref int score2, ref int score3, ref int score4, ref int score5)
{
int MaximumScore = 0;
int x = 0;
if (score1 > MaximumScore)
{
MaximumScore = score1;
}
if (score2 > MaximumScore)
{
MaximumScore = score2;
x = 1;
}
if (score3 > MaximumScore)
{
MaximumScore = score3;
x = 2;
}
if (score4 > MaximumScore)
{
MaximumScore = score4;
x = 3;
}
if (score5 > MaximumScore)
{
MaximumScore = score5;
x = 4;
}
Console.WriteLine("Max score is {0} from {1}", MaximumScore, divers[x]);
}
}
}
Appreciate you've already solved your problem, but thought I'd post this short example solution:
Console.WriteLine("The max score is " +
File.ReadAllLines(#"F:\1 -C# Programming\Coursework\DiverName.txt")
.Select(driver =>
{
int score;
do Console.WriteLine("Please Enter a Score between 0 and 10 for " + driver);
while (!int.TryParse(Console.ReadLine(), out score) || score < 0 || score > 10);
return score;
}).Max());
It's not completely clear from the code what do you really aim. At least, the code differs from the task description you provided. Anyway, I'd suggest such a wild guess, for example:
Update - I fixed the code to fit your needs, according to the working code you provided.
using System.IO;
using System.Linq;
namespace Diving_Championship
{
class Program
{
private class Diver
{
internal Diver(string name)
{
Name = name;
}
internal readonly string Name;
internal readonly int[] Scores = new int[5];
internal int TotalScore
{
get { return Scores.OrderBy(sc => sc).Skip(1).Take(3).Sum(); }
}
}
static void Main(string[] args)
{
string[] diverNames = File.ReadAllLines(#"F:\1 -C# Programming\Coursework\DiverName.txt");
List<Diver> divers = new List<Diver>();
for (int j = 0; j < 5; j++)
{
var diver = new Diver(diverNames[j]);
for (int i = 0; i < 5; i++)
{
int score;
do
{
Console.WriteLine("Please Enter a Score between 0 and 10 for {0}", diver.Name);
score = Convert.ToInt32(Console.ReadLine());
} while (score < 0 || score > 10);
diver.Scores[i] = score;
divers.Add(diver);
}
}
var MaxScore = divers.Max(d => d.TotalScore);
var Winner = divers.First(d => d.TotalScore == MaxScore);
Console.WriteLine("The winner is {0} with score {1}", Winner.Name, MaxScore); }
}
}
}
In the Main method, in the for loop, if you copy/paste/run whole program in visual, you'll see that i'm trying to end the game. First "if", if the user hasn't guessed; then attempts decrements by one and keeps guessing. The second "else if", if the user has guessed the PCArray, than the game ends and message shows. those work.
But, the first "else if", if the user has exhausted his attempts to guess, and hasn't guessed PCArray, than it should say "oh no, you couldn't guess..." Why is this not working.
I just want it to work so that if:
- user hasn't guessed but still has attempts, attempts decrements by 1 until 0.
- user has guessed the correct number, it says congrats.
- attempts are 0 and user still hasn't guessed number, then show "oh no..." message.
class Program
{
static void Main(string[] args)
{
string name;
Console.WriteLine("**************Let's play Master-Mined**************");
Console.WriteLine();
Console.Write("Please enter your name: ");
name = Console.ReadLine();
Console.WriteLine("Welcome {0}. Have fun!! ", name);
int numberCount = 0;
int difficultyLevel = 0;
int digitNumber = GetRandomNumberCount(numberCount);
Console.Write(digitNumber + " it is. Let's play.");
Console.WriteLine();
int[] PCArray = GenerateRandomNumbers(digitNumber);
Console.WriteLine("A " + digitNumber + "-digit number has been chosen. Each possible digit may be the number 1, 2, 3 or 4.");
Console.WriteLine(" ******");
int difficulty = GetGameDifficulty(difficultyLevel);
int attempts = difficulty * digitNumber;
Console.WriteLine("Enter your guess ({0} guesses remaining)", attempts);
int remaining = attempts;
for (int i = 0; i < attempts; i++)
{
int[] userArray = GetUserGuess(digitNumber);
int hits = CountHits(PCArray, userArray, attempts);
if ((hits != PCArray.Length) && (attempts > 0))
{
remaining--;
Console.WriteLine("Enter your guess ({0} guesses remaining)", remaining);
}
else if ((attempts < 1))
{
Console.WriteLine("Oh no {0}! You couldn't guess the right number.", name);
Console.WriteLine("The correct number is: ");
for (int j = 0; j < PCArray.Length; j++)
{
Console.Write(PCArray[j] + " ");
}
Console.WriteLine("Would you like to play again (Y/N)? ");
}
else if (hits == PCArray.Length)
{
attempts = 0;
Console.WriteLine("You win {0}!", name);
Console.WriteLine("The correct number is:");
for (int j = 0; j < PCArray.Length; j++)
{
Console.Write(PCArray[j] + " ");
}
}
}
Console.ReadLine();
}
public static int GetRandomNumberCount(int numberCount)
{
int number = 0;
do
{
try
{
Console.Write("How many numbers would you like to use in playing the game (4-10)? ");
number = int.Parse(Console.ReadLine());
Console.WriteLine();
}
catch
{
Console.WriteLine("You must pick a number between 4 and 10. Choose again.");
Console.WriteLine();
}
} while ((number < 4) || (number > 10));
return number;
}
public static int GetGameDifficulty(int difficultyLevel)
{
int difficulty = 0;
do
{
try
{
Console.Write("Choose a difficulty level (1=hard, 2=medium, 3=easy): ");
difficulty = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine(" Incorrect entry: Please re-enter.");
}
} while ((difficulty < 1) || (difficulty > 3));
return difficulty;
}
public static int[] GenerateRandomNumbers(int PCSize)
{
int eachNumber;
int[] randomNumber = new int[PCSize];
Random rnd = new Random();
for (int i = 0; i < randomNumber.Length; i++)
{
eachNumber = rnd.Next(1, 5);
randomNumber[i] = eachNumber;
Console.Write(eachNumber);
}
Console.WriteLine();
return randomNumber;
}
public static int[] GetUserGuess(int userSize)
{
int number = 0;
int[] userGuess = new int[userSize];
for (int i = 0; i < userGuess.Length; i++)
{
Console.Write("Digit {0}: ", (i + 1));
number = int.Parse(Console.ReadLine());
userGuess[i] = number;
//Console.Write(number);
}
Console.WriteLine();
Console.Write("Your guess: ");
for (int i = 0; i < userGuess.Length; i++)
{
Console.Write(userGuess[i] + " ");
}
Console.WriteLine();
return userGuess;
}
public static int CountHits(int[] PCArray, int[] userArray, int attempts)
{
int hit = 0;
int miss = 0;
int hits = 0;
for (int i = 0; i < PCArray.Length; i++)
{
if (PCArray[i] == userArray[i])
{
hit = hit + 1;
hits = hit;
}
else
{
miss = miss + 1;
}
}
Console.WriteLine("Results: {0} Hit(s), {1} Miss(es)", hit, miss);
return hits;
}
}
First of all, you should rethink your code, because the flow control is scattered throughout your code. For example, you don't need both attempts and remaining, they control the same thing.
Using two variables to control the same thing is what is causing your problem. The first two ifs in your for should be like this:
if (hits != PCArray.Length && remaining > 1)
and
else if (remaining == 1)
Note I removed the unnecessary parenthesis. With these changes, your application works, although the code is not too pretty.
A simple way of enhancing your code is to first check for the right result, and if it's not, then decrease the attempts variable and finally check for its value. That's why with your code as it is, the if should compare to 1 instead of 0.
The hits variable in your CountHits method is totally unnecessary; you should just return hit. Actually the miss variable can be avoided too, you can calculate it. Also remember to use the ++ operator.
But as I said first, the important thing is not to make it work but to organize your code properly. Later I will post my version.
My version, it's not the most beautiful thing in the world but I didn't want to change much of your code structure:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("************** Let's play Master-Mind **************\n");
string name = GetPlayerName();
do
{
Play(name);
Console.Write("\nWould you like to play again (Y/N)? ");
}
while (Console.ReadLine().ToUpper() == "Y");
}
private static void Play(string name)
{
int numberCount = GetRandomNumberCount();
Console.Write(numberCount + " it is. Let's play.");
Console.WriteLine();
int[] PCArray = GenerateRandomNumbers(numberCount);
Console.WriteLine("A {0}-digit number has been chosen. Each possible digit may be the number 1 to 4.\n", numberCount);
int difficulty = GetGameDifficulty();
bool won = false;
for (int allowedAttempts = difficulty * numberCount; allowedAttempts > 0 && !won; allowedAttempts--)
{
Console.WriteLine("\nEnter your guess ({0} guesses remaining)", allowedAttempts);
int[] userArray = GetUserGuess(numberCount);
if (CountHits(PCArray, userArray) == numberCount)
won = true;
}
if (won)
Console.WriteLine("You win, {0}!", name);
else
Console.WriteLine("Oh no, {0}! You couldn't guess the right number.", name);
Console.Write("The correct number is: ");
for (int j = 0; j < numberCount; j++)
Console.Write(PCArray[j] + " ");
Console.WriteLine();
}
private static string GetPlayerName()
{
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Welcome, {0}. Have fun!!\n", name);
return name;
}
public static int GetRandomNumberCount()
{
int number;
Console.Write("How many numbers would you like to use in playing the game (4-10)? ");
while (!int.TryParse(Console.ReadLine(), out number) || number < 4 || number > 10)
Console.WriteLine("You must pick a number between 4 and 10. Choose again.");
return number;
}
public static int GetGameDifficulty()
{
int difficulty = 0;
Console.Write("Choose a difficulty level (1=hard, 2=medium, 3=easy): ");
while (!int.TryParse(Console.ReadLine(), out difficulty) || difficulty < 1 || difficulty > 3)
Console.WriteLine("Incorrect entry: Please re-enter.");
return difficulty;
}
public static int[] GenerateRandomNumbers(int PCSize)
{
int eachNumber;
int[] randomNumber = new int[PCSize];
Random rnd = new Random();
Console.Write("PC number: ");
for (int i = 0; i < PCSize; i++)
{
eachNumber = rnd.Next(1, 5);
randomNumber[i] = eachNumber;
Console.Write(eachNumber);
}
Console.WriteLine();
return randomNumber;
}
public static int[] GetUserGuess(int userSize)
{
int number = 0;
int[] userGuess = new int[userSize];
for (int i = 0; i < userSize; i++)
{
Console.Write("Digit {0}: ", (i + 1));
while (!int.TryParse(Console.ReadLine(), out number) || number < 1 || number > 4)
Console.WriteLine("Invalid number!");
userGuess[i] = number;
}
Console.WriteLine();
Console.Write("Your guess: ");
for (int i = 0; i < userSize; i++)
{
Console.Write(userGuess[i] + " ");
}
Console.WriteLine();
return userGuess;
}
public static int CountHits(int[] PCArray, int[] userArray)
{
int hits = 0;
for (int i = 0; i < PCArray.Length; i++)
{
if (PCArray[i] == userArray[i])
hits++;
}
Console.WriteLine("Results: {0} Hit(s), {1} Miss(es)", hits, PCArray.Length - hits);
return hits;
}
}
It does a few more validations and it even actually lets you play again! ;)