Saving values within if statement C# - c#

I'm a newbie at C# and I'm having some difficulties writing a program that is going to let you save values in a variable, everything is working fine, except I can't save values into my variable. Here's the code:
while (true)
{
//Menu
Console.WriteLine (" \n\tWelcome!");
Console.WriteLine (" \t[1]Store value");
Console.WriteLine (" \t[2]Write message");
Console.WriteLine (" \t[3]Clear the console");
Console.WriteLine (" \t[4]Shut down program");
Console.Write("\tChoose: ");
//Users choice
int choice = Convert.ToInt32 (Console.ReadLine ());
//Users message
string usrMsg = null;
//if statement
if (choice == 1) {
usrMsg += Console.ReadLine ();
} else if (choice == 2) {
Console.WriteLine (usrMsg);
} else if (choice == 3) {
//Shuts down program
break;
} else if (choice == 4) {
//Clear program
Console.Clear ();
}
else
{
Console.WriteLine("please enter a number between 1-4");
}
}

You just move the usrMsg variable out of while block as a global the value will be saved.
//Users message
string usrMsg = null;
while (true)
{
//Menu
Console.WriteLine(" \n\tWelcome!");
Console.WriteLine(" \t[1]Store value");
Console.WriteLine(" \t[2]Write message");
Console.WriteLine(" \t[3]Clear the console");
Console.WriteLine(" \t[4SShut down program");
Console.Write("\tChoose: ");
//Users choice
int choice = Convert.ToInt32(Console.ReadLine());
//if statement
if (choice == 1)
{
usrMsg += Console.ReadLine();
}
else if (choice == 2)
{
Console.WriteLine(usrMsg);
}
else if (choice == 3)
{
//Shuts down program
break;
}
else if (choice == 4)
{
//Clear program
Console.Clear();
}
else
{
Console.WriteLine("please enter a number between 1-4");
}
}

When this runs it always creates userMsg as null. That means that at best it will 'save' only 1 value when the user chooses '1'. However, this will never get displayed if the user selects '2' as when the user gets to the menu again userMsg will have been set to null again.
My assumption is that you're trying to save the number of times someone has selected '1' and then display that if the user then hits option '2'.
Stick this:
//Users message
string usrMsg = null;
outside of the 'while' loop.

Related

How would I be able to make the program stop with only a specific input in C#

I am very new to C# and I have just created my first program, which is your classic "number guesser".
In my program, after the user has guessed the correct number, I want to give them an option where they can either type "Y" or "N" to continue or end the game.
Where my issue lies is, if the user were to type in the letter "G" at this stage, the program would continue and ask the user to input another number.
How do I enable my code to keep looping at this stage until either Y is pressed to continue the game or N is pressed to end the program?
using System;
// Namespace
namespace NumberGuesser
{
// Main Class
class Program
{
// Entry Point Method
static void Main(string[] args)
{
GetAppInfo(); // Run GetAppInfo function to get info
GreetUser(); // Ask for user's name and greet
while (true)
{
// Create a new Random object
Random random = new Random();
// Initial correct number
int correctNumber = random.Next(1, 11);
// Initial guess var
int guess = 0;
// Ask user for number
Console.WriteLine("Guess a number between 1 and 10:");
// While guess is not correct
while (guess != correctNumber)
{
// Get users input
string input = Console.ReadLine();
// Make sure it's a number
if (!int.TryParse(input, out guess))
{
// Print error message
PrintColourMessage(ConsoleColor.Red, "Please user an actual number.");
// Keep going
continue;
}
// Make sure the number guessed is between 1 - 10
if (guess > 10)
{
// Print error message
PrintColourMessage(ConsoleColor.Red, "Please enter a number from 1 to 10.");
// Keep going
continue;
}
// Cast to int and put in guess
guess = Int32.Parse(input);
// Match guess to correct number
if (guess != correctNumber)
{
// Print error message
PrintColourMessage(ConsoleColor.Red, "Wrong number, please try again.");
}
}
// Print success message
PrintColourMessage(ConsoleColor.Yellow, "You are CORRECT!!!");
// Ask to play again
Console.WriteLine("Play again? [Y or N]");
// Get answer
string answer = Console.ReadLine().ToUpper();
if (answer == "Y")
{
continue;
}
else if (answer == "N")
{
return;
}
else
{
return;
}
}
}
// Get and display app info
static void GetAppInfo()
{
// Set app vars
string appName = "Number Guesser";
string appVersion = "1.0.0";
string appAuthor = "Jack Thomas";
// Change text colour
Console.ForegroundColor = ConsoleColor.Green;
// Write out app info
Console.WriteLine("{0}: Version {1} by {2}", appName, appVersion, appAuthor);
// Reset text colour
Console.ResetColor();
}
// Ask user's name and greet
static void GreetUser()
{
// Ask users name
Console.WriteLine("What is your name?");
// Get user input
string inputName = Console.ReadLine();
Console.WriteLine("Hello {0}, let's play a game...", inputName);
}
// Print colour message
static void PrintColourMessage(ConsoleColor color, string message)
{
// Change text colour
Console.ForegroundColor = color;
// Prints message
Console.WriteLine(message);
// Reset text colour
Console.ResetColor();
}
}
}
Just instead of doing this:
// Ask to play again
Console.WriteLine("Play again? [Y or N]");
// Get answer
string answer = Console.ReadLine().ToUpper();
if (answer == "Y")
{
continue;
}
else if (answer == "N")
{
return;
}
do that:
// Ask to play again
Console.WriteLine("Play again? [Y or N]");
bool toContinue = false;
bool invalidResponse = true;
while(invalidResponse) {
// Get answer
string answer = Console.ReadLine().ToUpper();
if (answer == "Y")
{
toContinue = true;
invalidResponse = false;
}
else if (answer == "N")
{
invalidResponse = false;
}
}
if(toContinue != true) return;
I've created while loop wich loops while invalidResponse variable is true, invalidResponse is true when we not entered any of these characters "Y" or "N".
You can also make Console.WriteLine when user enters invalid response.
If user does not entered "Y" it sets toContinue to false and it ends program.

How to make the console accept input from the Enter key only?

I'd like to make the C# console only accept input from the Enter key on the startup screen.
I've made it so that it closes the console when anything but the Enter key is pressed.
How can I make it so that the console only accepts input from the Enter key so that the application doesn't close when I press anything else, and then receive normal input afterwards?
class Program
{
public static void ClearKeyBuffer()
{
while (Console.KeyAvailable)
Console.ReadKey(true);
}
public static void Main (string[] args)
{
int attempts = 0;
int displayattempts = 5;
bool validentry;
Console.WriteLine("Please press enter to begin");
var key = System.Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
while (attempts < 5)
{
string input;
attempts = (attempts + 1);
Console.Clear();
Console.WriteLine("Please wait...");
Thread.Sleep(5000);
Console.Clear();
Console.WriteLine("Please enter your user number.");
Console.WriteLine("Attempts Remaining:" + displayattempts);
ClearKeyBuffer();
Console.WriteLine(" ");
input = Console.ReadLine();
{
if (input == "5573")
{
validentry = true;
}
else
{
validentry = false;
}
if (validentry == false)
{
displayattempts = (displayattempts - 1);
Console.Clear();
Console.WriteLine("Error: Invalid number ID entered. Please wait 5
seconds, and try again.");
Thread.Sleep(5000);
}
else if (validentry == true)
{
Console.Clear();
Console.WriteLine("Welcome Samuel");
ValidUserEntry();
}
}
}
}
if (displayattempts == 0)
{
Console.Clear();
Console.WriteLine("Error: You have entered the wrong number ID too many times.
This system will now close in 5 seconds...");
Thread.Sleep(5000);
Environment.Exit(0);
}
}
public static void ValidUserEntry()
{
ClearKeyBuffer();
Console.Clear();
Console.WriteLine("Please wait...");
Thread.Sleep(5000);
ClearKeyBuffer();
Console.Clear();
Console.WriteLine("What would you like to do?");
Console.ReadLine();
}
}
Add this line before first if. Then remove if statement and the var key... line.
while (Console.ReadKey(true).Key != ConsoleKey.Enter);
Alternative, more verbose version:
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
} while (key.Key != ConsoleKey.Enter);

Error detected trying to receive input as an integer in C#

I am trying to make a simple program where the user tries to guess numbers between 1 and 25 until they guess the right one. I am trying to make the input received as an integer so that I can use greater than and less than signs. When I use the command I found on another answer in this forum, it says that there is an error. What am I doing wrong?
int score = 0;
int add = 1;
while (add == 1)
{
Console.WriteLine("Guess A Number Between 1 and 25");
string input = int.Parse(Console.ReadLine());
score += add;
if (input == 18)
{
Console.WriteLine("You Did It!");
Console.WriteLine("Your Score was " + score);
break;
}
else if (input > 25)
{
Console.WriteLine("Error.");
}
else
{
Console.WriteLine("Try Again. Score: " + score);
}
}
Store their response from ReadLine() as a String, then use int.TryParse() to attempt to convert that String to an Integer. The code below is written to show you all the possible states that could occur using if else blocks. I've also used a bool to indicate when the game should end instead of using a break statement:
static void Main(string[] args)
{
int number;
string input;
bool guessed = false;
int score = 0;
while (!guessed)
{
Console.Write("Guess A Number Between 1 and 25: ");
input = Console.ReadLine();
if (int.TryParse(input, out number))
{
if(number>=1 && number<=25)
{
score++;
if (number == 18)
{
guessed = true;
Console.WriteLine("You Did It!");
Console.WriteLine("Your Score was " + score);
}
else
{
Console.WriteLine("Try Again. Score: " + score);
}
}
else
{
Console.WriteLine("Number must be between 1 and 25!");
}
}
else
{
Console.WriteLine("That's not a number!");
}
Console.WriteLine();
}
Console.Write("Press Enter to Quit.");
Console.ReadLine();
}

How would you go about refreshing your application once you have pressed any key? C#

I'm currently creating a program; I cannot figure out how to refresh the application after a key is pressed.
So far I have:
Console.WriteLine("Press Any Key To Refresh");
Console.ReadKey();
Full Code Block
class Program
{
static void Main(string[] args)
{
int userInput;
DirectoryInfo folderInfo = new DirectoryInfo("C:\\Windows");
FileInfo[] files = folderInfo.GetFiles();
Console.WriteLine("Welcome To File Manager");
Console.WriteLine("");
Console.WriteLine("Current Folder: C:\\Windows");
Console.WriteLine("");
Console.WriteLine("Please Select An Opion Between 1 To 4:"); // Displays Options for Main Menu.
Console.WriteLine("1. ");
Console.WriteLine("2. ");
Console.WriteLine("3. ");
Console.WriteLine("4. ");
userInput =int.Parse(Console.ReadLine());
{
if (userInput == 1)
{
Console.WriteLine("Files in C:\\Windows:");
for (int index = 0; index < files.Length; index++) // Lists The Files Within The Speficied Folder C:\\Windows - Also Assigns Numerical Value To Each File.
{
Console.WriteLine("{0}" , index + ". " + 1 + files[index].Name + " (" +(files[index].Length) + ")");
}
Console.WriteLine("Press Any Key To Return To Main Menu");
Console.ReadKey();
}
else if (userInput == 2)
{
// code for option 2
}
else if (userInput == 3)
{
// Code for option 3
}
else if (userInput == 4)
{
// Closes Application.
}
} while (userInput != 4);
Once the operation within option (1) has ran, the message; "Press Any Key To Refresh" appears - Afterwards I'd like it to refresh the application once a key is pressed!
I hope this clarifies what I was asking!
Many Thanks
- Dan
This may help if I understood correctly what you want to accomplish.
bool isClicked = true;
while(isClicked)
{
Console.WriteLine("Please Select An Opion Between 1 To 4:");
int userInput = int.Parse(Console.ReadLine());
switch (userInput)
{
case 1:
Console.WriteLine("Press Any Key To Return To Main Menu");
Console.ReadKey();
//isClicked = false; // Used to suspend the operation
break;
case 2:
// code for option 2
break;
case 3:
// code for option 3
break;
case 4:
// code for option 4
break;
default:
Console.WriteLine("Error occured");
break;
}
}

How to check user input with if command

Not sure if I'm overlooking something really simple but I'm trying to make a program that allows a user to enter 1 of 2 letters and then run code based on the input. Seems simple enough but I've run into several errors with all the ways I thought this could work. Here is the code:
string name = (Console.ReadLine());
Console.WriteLine("Is " + name + " ok?");
Console.WriteLine("\n(Y)es\n(N)o");
char ansys = Console.ReadKey();
if (ansys = ConsoleKey.Y)
Console.Clear();
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only");
}
I added in the else portion (unfinished)just to get an idea if If i'm going the right direction with the intended goal as well. Would I be able to make an else statement that triggers if neither Y or N is pressed this way?
Well, first of all, you are making an assignment, not comparing:
if (ansys.Key = ConsoleKey.Y)
is wrong, use:
if (ansys.Key == ConsoleKey.X)
== is comparison, = is assignment. Don't confuse them, it may cause serious problems.
For you question, if you simply add an else if statement checking for "No" answer, then else statement won't be triggered if Y or N is pressed. If at least if statement is executed, else statement won't be executed.
Your code should look like:
if (ansys == ConsoleKey.Y) {
// code if yes
}
else if (ansys == ConsoleKey.N) {
// code if no
}
else {
// code if neither
}
Edit:
Since my primary language is not C#, I looked at documentation to check my answer. I figured out that if you use ReadKey() it does not return a ConsoleKey, it returns struct ConsoleKeyInfo. You need to use Key member of the ConsoleKeyInfo to access the pressed key. Please re-check the code.
Try this approach:
ConsoleKeyInfo cki;
cki = Console.ReadKey();
if (cki.Key == ConsoleKey.Y)
{
Console.Clear();
}
else if (cki.Key == Console.N)
{
Console.Clear();
}
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only");
}
You can find th examples here: ReadKey - examples
Try this:
string name = (Console.ReadLine());
Console.WriteLine("Is " + name + " ok?");
Console.WriteLine("\n(Y)es\n(N)o");
var ansys = Console.ReadKey();
if (ansys.KeyChar == 'y' || ansys.KeyChar == 'Y')
{
//Handle yes case
}
if (ansys.KeyChar == 'n' || ansys.KeyChar == 'N')
{
//Handle no case
}
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only");
}
Try this (couldnt test it)
This will ask for the name until the confirmation answer is Y
If the input when asked Y or N is another thing, it will ask again for the name confirmation.
string name = "";
while (name.equals(""))
{
name = (Console.ReadLine());
Console.WriteLine("Is " + name + " ok?");
String answer = "";
while(answer.equals(""))
{
Console.WriteLine("\n(Y)es\n(N)o");
char ansys = Console.ReadKey();
if (ansys == ConsoleKey.Y || ansys == ConsoleKey.N)
{
answer = ansys.ToString();
Console.Clear();
}
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only!!");
}
}
if(!answer.equals("Y"))
name = "";
}
Im not sure if ansys.ToString() is a valid method, and if that returns the "Y" string in case the key pressed was Y

Categories

Resources