Skip to content
Permalink
1a452f980c
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
81 lines (72 sloc) 1.75 KB
using System;
using System.Collections.Generic;
namespace NumberGuesser
{
class Program
{
static void Main(string[] args)
{
// Step 1: Generate random number between two integers
Random rnd = new Random();
int secretNumber = rnd.Next(1, 101);
// Step 2: Take inputs that are guesses at the random number
List<int> responseHistory = new List<int>();
while (true)
{
Console.WriteLine("What is your number guess?");
string response = Console.ReadLine();
// Totally acceptable way to convert string to int
// int responseNumber = Convert.ToInt32(response);
//// Fancy way to convert string to integer
//int responseNumber;
//bool success = int.TryParse(response, out responseNumber);
//if (success == false)
//{
// Console.WriteLine("Invalid input!");
// continue;
//}
int responseNumber = 0;
try
{
responseNumber = Convert.ToInt32(response);
}
catch (Exception ex)
{
// Do stuff in case it fails
Console.WriteLine("Invalid input!");
Console.WriteLine(ex.Message);
continue;
}
finally
{
Console.WriteLine("Does this execute?");
}
responseHistory.Add(responseNumber);
if (secretNumber == responseNumber)
{
// The user was correct
Console.WriteLine("You're correct!");
break;
}
else
{
// The user was incorrect
if (responseNumber > secretNumber)
{
Console.WriteLine("Too high, try again!");
}
else
{
Console.WriteLine("Too low, try again!");
}
string guessHistory = "Guess history: ";
foreach (int value in responseHistory)
{
guessHistory = guessHistory + value + ", ";
}
Console.WriteLine(guessHistory);
}
}
}
}
}