Main Menu for a mastermind game - c#

I am trying to create the menu for a mastermind game which can be ran in a command prompt using C#. The issue I am running into is capturing the users input for the menu. If they enter a 2 then it should display that they entered the number two and if not then it would say they have not displayed the number two.
The issue I am having is that it wont turn the users input into a working integer and will either come up saying that it can't explicitly convert from System.ConsoleKeyInfo to int or string to int.
using System;
namespace MasterMind
{
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" MasterMind's Main Menu");
Console.WriteLine(" 1: Play");
Console.WriteLine(" 2: Help");
Console.WriteLine(" 0: Exit");
int userinput = Console.ReadKey();
if (Nuserinput == 2);
{
Console.WriteLine("This is a number 2");
}
else
{
Console.WriteLine("This is not a number 2");
}
}
}
}

Console.ReadKey() returns a ConsoleKeyInfo object, which is not an int object. You can get a char from that, for example:
var key = Console.ReadKey();
var keyChar = key.KeyChar;
If you expect that char value to represent an integer, you can convert it to one:
int keyInt = (int)Char.GetNumericValue(keyChar);
Aside from other error checking you might want to put in place in case the user doesn't enter a valid integer, this would at least get your the integer value you're looking for.

Console.ReadKey() returns a ConsoleKeyInfo, so you'll need to do something like this:
ConsoleKeyInfo data = Console.ReadKey();
int num;
if (int.TryParse(data.KeyChar.ToString(), out num) && num == 2)
{
Console.WriteLine("This is a number 2");
}else{
Console.WriteLine("This is not a number 2");
}

Change your
int userinput = Console.ReadKey();
if (Nuserinput == 2)
To:
string userInput = Console.ReadKey().KeyChar.ToString();
if(input == "2")
Or covert the string to an int as shown in other answers. But for this, a string works fine.

Related

How to prevent input of null enter in C# [duplicate]

This question already has answers here:
check for valid number input - console application
(5 answers)
Allow To Only Input A Number - C#
(1 answer)
Closed 2 years ago.
I have just started a table programme. I am just a trainee learning C# from internet, so I am not so good in this.
I just wanted the programme to run according to the user. I want that if the user hits enter simply, the programme should not crash. That is I just wanted to know how to prevent null enter. This is the code is used:
The "______" which used if for writing a line
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace tables
{
class Program
{
static void Main(string[] args)
{
goto found;
found:
Console.WriteLine("");
string textToEnter = "MULTIPLATION TABLES";
Console.WriteLine(String.Format("{0," + ((Console.WindowWidth / 2) + (textToEnter.Length / 2)) + "}", textToEnter));
Console.WriteLine("");
Console.WriteLine("________________________________________________________________________________");
Console.WriteLine("");
int num, j, i;
Console.Write("enter the number of which table u need ? :- ");
num = Convert.ToInt32( Console.ReadLine());
while (num == 0)
{
Console.WriteLine("please enter a valid input");
Console.Write("enter the number of which table u need ? :- ");
num = Convert.ToInt32(Console.ReadLine());
}
Console.Write("enter the number till which the table need to be ? :- ");
j = Convert.ToInt32(Console.ReadLine());
while (j == 0)
{
Console.WriteLine("please enter a valid input");
Console.Write("enter the number till which the table need to be ? :- ");
j = Convert.ToInt32(Console.ReadLine());
}
i = Convert.ToInt32(j);
for (j=1; ; j++)
{
if (j > i)
{
break;
}
Console.WriteLine(num + " * " + j + " = " + num * j);
}
string str;
Console.Write("do you want to continue? (y/n) :- " );
str= Console.ReadLine();
foreach (char ch in str)
{
if (ch == 'y')
{
goto found;
}
else if (ch=='n' )
{
Console.WriteLine("");
Console.WriteLine("THANK YOU FOR USING MY PRODUCT");
}
else
{
Console.WriteLine("please enter a valid input");
}
}
Console.ReadKey();
}
}
}
As suggested in the comments, I'd use int.TryParse(), but inside a do...while() loop. Use a separate flag (boolean) to track whether the user should keep trying again:
bool invalid;
int num, j, i;
do
{
invalid = true;
Console.Write("enter the number of which table u need ? :- ");
String response = Console.ReadLine();
if (int.TryParse(response, out num))
{
invalid = false;
}
else
{
Console.WriteLine("Invalid input. Please try again.");
}
} while (invalid);
// ...repeat the above do...while() block for "j" and "i"...
When you're accepting user input, it's important to perform validation on it. You can't assume that the user will always enter correctly formatted data that your program will be able to work with. As you discovered, a user who hits enter will give you an empty string (""), which can't be parsed to anything.
C# has several ways of attempting parsing. The first, which you're using, is Convert.ToInt32(), which throws an exception if the input it receives is not, in fact, a number. You have to catch the exception with a try/catch block, like so:
try
{
num = Convert.ToInt32(Console.ReadLine());
}
catch(FormatException ex)
{
Console.WriteLine("You didn't enter a proper number!");
}
However, in general, exceptions should be, well, exceptional. They should only be relied upon when rare failures occur, because unwinding the call stack can be expensive.
I would argue that C# has a better method for you to use in this instance: Int32.TryParse()
You can see the documentation here.
TryParse takes two parameters, the thing you're trying to parse (convert), and then a number to store the value in. It returns true or false, indicating if it succeeded or failed in converting the number.
You might use it like this:
var success = Int32.TryParse(Console.ReadLine(), num);
if (success)
{
// do something with 'num' -- it has a valid value now.
}
else
{
// Warn the user, perhaps prompt them to try again
Console.WriteLine("That wasn't a valid number!");
}
You can use a methode to get a safe int value:
private static int ReadIntValue(string psMessage)
{
int lnInt;
string lsValue = string.Empty;
do
{
Console.Write(psMessage);
lsValue = Console.ReadLine();
} while (!int.TryParse(lsValue, out lnInt));
return lnInt;
}
And then use this:
num = ReadIntValue("enter the number of which table u need ? :- ");

How to loop a Console.ReadLine to the infinite?

Hello i'm trying to create a calculator game but it loops only 2 times and (idk why)not til the user finds the result with input. And i'll later see how to make a random generator of numbers instead of writing them by myself in the code. Ty for helping.
Yassine
using System;
namespace G
{
class Program
{
static void Main(string[] args)
{
Calcul(2, 2);
}
static void Calcul(int nombre1, int nombre2)
{
int result = nombre1 + nombre2;
Console.WriteLine("Combien font " + nombre1 + " + " + nombre2);
int supposed = int.Parse(Console.ReadLine());
if(result != supposed)
{
Console.WriteLine("Try again!");
supposed = int.Parse(Console.ReadLine());
}
else
{
Console.Clear();
Console.WriteLine("Correct!");
}
}
}
}
You can change your if statement to a while loop whose condition is that the input does not match the result. We can also use int.TryParse with Console.ReadLine to handle cases where the user doesn't enter a valid number. This works by taking an out parameter that gets set to the parsed value if it's successful, and it returns a bool that indicates success. Perfect for a loop condition!
Then you can put the "success" message after the body of the while loop (because the only way to exit the loop is to get the correct answer). It would look something like:
static void Calcul(int nombre1, int nombre2)
{
int result = nombre1 + nombre2;
int input;
Console.Write($"Combien font {nombre1} + {nombre2} = ");
while (!int.TryParse(Console.ReadLine(), out input) || input != result)
{
Console.WriteLine("Incorrect, please try again.");
Console.Write($"Combien font {nombre1} + {nombre2} = ");
}
Console.WriteLine("Correct! Press any key to exit.");
Console.ReadKey();
}

Need to enter escape key to end program

I am writing a simple calculator where the user can perform operations and end the program by entering -1.
How can I modify how I take input from the user so that they can use the escape key instead of entering -1?
using System;
namespace A_4
{
class Calculator
{
public static void Main(string[] args)
{
Console.WriteLine("\tSimple Calculator");
while (true)
{
Console.WriteLine("********************************");
Console.Write("Enter First Number: ");
double operand1 = Convert.ToDouble(Console.ReadLine());
if (operand1 == -1)
{
break;
}
Console.Write("\nEnter Second Number: ");
double operand2 = Convert.ToDouble(Console.ReadLine());
if (operand2 == -1)
{
break;
}
Console.Write("\nEnter operator +, -, *, /): ");
// ... operate on the entered input
}
}
}
Since you want to get a specific key, you'll not be able to use Console.ReadLine, you have to read each character to be able to determine if ESC was pressed.
The best would be to create a helper method to get user input:
public static double GetUserInput()
{
string numbersEntered = "";
ConsoleKeyInfo lastKey;
// read keys until Enter is pressed
while ((lastKey = Console.ReadKey()).Key != ConsoleKey.Enter)
{
// if Escape is pressed, exit
if (lastKey.Key == ConsoleKey.Escape)
{
return -1;
}
// otherwise, add the key entered to the input
numbersEntered += lastKey.KeyChar.ToString();
}
// and convert the final number to double
return Convert.ToDouble(numbersEntered);
}
With that, you can just do double operand1 = GetUserInput(); and you know that if it's -1 (as an example), you have to exit.

C# input has to be 5 digits

I have a question that asks the user to enter a student number, how can I make it so it will only accept a 5 digit number. The input is being added to an object like
console.writeline("Enter the student number: ");
then
studentObject.StudentNumber = int.Parse(Console.Readline());
I've tried using
if (Console.ReadLine().Length != 5)
{
//Do this
}
else
{
//Do this
}
But it won't work, the .Length says can't convert type int to bool. I'm stuck, any help please?
You can use regular expressions:
String input;
do {
Console.WriteLine("Please enter student number:");
input = Console.ReadLine();
}
while (!Regex.IsMatch(input, #"^\d{5}$")); // <- five digits expected
// input contains 5 digit string
int number = int.Parse(number);
P.S. In case that the input should be "five digit number, not starting with zero" the regular expression has to be changed to something like that:
while (!Regex.IsMatch("12345", #"^[1-9]\d{4}$")); // five digits, not zero-starting
Probably not the answer to your question, however one thing I noticed:
if you are using Console.Readline() in your if-statement and then want to store it in the studentObject you will need to store it in a variable first. Calling Console.Readline(); again to store it in the studentObject will cause another input to be expected, which nullifies your attempt to validate the input.
Something like this:
static void Main(string[] args)
{
Console.WriteLine("Please enter student number:");
//get the user input
var number = Console.ReadLine();
if (number.Length != 5)
{
Console.WriteLine("Invalid format.");
}
else
{
Console.WriteLine("Yay it works");
}
Console.ReadLine();
}
var input = Console.ReadLine();
int i;
if (input.Length > 0 && input.Length < 6 && Int32.TryParse(input, out i))
// i has 5 digit;
else
// i has zero
char[] cc = Console.Read().ToString().ToCharArray();
if (char.IsDigit(cc[0])&&
char.IsDigit(cc[1])&&
char.IsDigit(cc[2])&&
char.IsDigit(cc[3])&&
char.IsDigit(cc[4]))
{
//Life's GOOD!
}else { //bad input}
Note: I'm self-taught & don't have much knowledge. Correct me if wrong.

C# Console Program Loop Issue

I have tried to create a C# program that gives the user 3 options:
Create name (gets the user to enter their first name and surname and display it as J.Blogg)
Factorial of a number (outputs as for example 5x4x3x2x1 =120 which is the factorial of 5
Quit
I have the program work fine but when I try picking option 1 (create name) and then option 2 it goes to option 1 instead and then it doesn't lets me Quit (option 3).
I'm new to programming so it could be simple but I can't see where i'm going wrong,
Any help would be very greatful.
I want to keep the same layout, I think my problem could be the loops but any help and improvement would be great.
static void Main(string[] args)
{
//The value returned from the topmenu method is stored in a variable called useroption
int useroption;
useroption = topmenu();
// excute while loop untill option is not 1-3
do
{
if (useroption == 1)
{
Console.Clear();
Createname();
//break;
}
if (useroption == 2)
{
Console.Clear();
factorial();
// break;
}
if (useroption == 3)
{
Console.Clear();
Console.WriteLine("Thank you for using my program, Good bye !!!");
// break;
}
//topmenu();
}
while (useroption != 3);
Console.ReadKey();
}
//This method present the user with an menu which the user has a choice of 3 options
static int topmenu()
{
int option;
string option_str;
Console.Clear();
Console.WriteLine("********************************************************************************");
Console.WriteLine("********************************************************************************");
Console.WriteLine("********* OPTION 1 : Enter your name *********");
Console.WriteLine("********* OPTION 2 : Enter the number you want to factorise *********");
Console.WriteLine("********* OPTION 3 : Quit *********");
Console.WriteLine("********************************************************************************");
Console.WriteLine("********************************************************************************");
option_str = Console.ReadLine();
option = Convert.ToInt32(option_str);
Console.Clear();
if (option < 0 || option > 3)
{
Console.WriteLine("You have enter an invald option,");
Console.WriteLine("Please chose a option between 1-3 (Please press any key to return to main menu)");
Console.ReadLine();
Console.Clear();
topmenu();
}
else
{
Console.WriteLine("You have chosen option: " + option + " (Please press any key continue)");
}
Console.ReadKey();
return option;
}
//this method asks user to enter their name (1st name then surname) and presents it back to the user as their intial(1st name) and surname
static void Createname()
{
string firstname, surname, firstname_str, surname_str, userfullname;
Console.Clear();
Console.WriteLine("Please enter your first name ");
firstname_str = Console.ReadLine();
firstname = Convert.ToString(firstname_str);
Console.Clear();
Console.WriteLine("Please enter your surname name ");
surname_str = Console.ReadLine();
surname = Convert.ToString(surname_str);
Console.Clear();
userfullname = firstname + surname;
Console.WriteLine("You have entered your name as " + firstname[0] + "." + surname);
Console.WriteLine("(Please press any key to return to main menu)");
Console.ReadKey();
topmenu();
}
//this method asks the user to enter a number and returns the factorial of that number
static double factorial()
{
string number_str;
double factorial = 1;
Console.WriteLine("Please enter number");
number_str = Console.ReadLine();
int num = Convert.ToInt32(number_str);
// If statement is used so when the user inputs 0, INVALID is outputed
if (num <= 0)
{
Console.WriteLine("You have enter an invald option");
Console.WriteLine("Please enter number");
number_str = Console.ReadLine();
Console.Clear();
num = Convert.ToInt32(number_str);
//Console.Clear();
//topmenu();
//number_str = Console.ReadLine();
}
if (num >= 0)
{
while (num != 0)
{
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
Console.Write(i + " * ");
}
Console.WriteLine("= "+factorial+ " which is factorial of " + number_str.ToString() );
Console.WriteLine("(please any key to return to main menu)");
Console.ReadKey();
Console.Clear();
topmenu();
}
}
return factorial;
}
}
}
Just put these line inside do...while
int useroption;
useroption = topmenu();
rearrange as following...
int useroption;
// excute while loop untill option is not 1-3
do
{
useroption = topmenu();
and your program will work fine
The full code is here : http://pastebin.com/fCh0ttUY
First of al, set useroption to 0 after executing some code. Otherwise it will keep executing it.
Second, ReadKey() right before your while statement. Otherwise you won't be able to read the input.
The issue is that although you display topmenu again you never re-assign the value of useroption.
As gypsyCoder said, moving the display of your menu inside the do{}while() block will fix your issue because it will cause the useroption to be re-assigned each time round the loop.

Categories

Resources