I have created a small project . and here is it:
class Program
{
public static void Main()
{
Console.WriteLine("Welcome");
Console.WriteLine("1 to go to Data Files ");
Console.WriteLine("type quit to exit");
string input = Console.ReadLine();
if (input == "1")
{
Data go = new Data();
}
else if (input == "quit")
{
}
}
}
When user type quit. I want my program to exit. anyone help me, please
You just need something like this:
else if (input == "quit")
{
return;
}
Update: based on your comments I think you're looking for something like this:
class Program
{
public static void Main()
{
while(true)
{
Console.WriteLine("Welcome");
Console.WriteLine("1 to go to Data Files ");
Console.WriteLine("type quit to exit");
string input = Console.ReadLine();
if (input == "1")
{
Data go = new Data();
}
else if (input == "quit")
{
return;
}
else
{
Console.WriteLine("invalid option");
}
}
}
}
You just can use Environment.Exit(code). where code is integer representation of standard application-exit-codes like return 0 or return 1 in world of C++.
Related
Suppose a user is asked for the manual. Now we all know that manuals are handy and extensive, how do I collapse/clear for instance so that the user can proceed to the next activity? By pressing C after pressing M, I want the user to immediately jump to the next acitivity.
How do I remove this?
Here is the code:
static void Main(string[] args)
{
Console.WriteLine("Do you want to play the game?\nPress Y to continue\tPress M to view the rules\tEnter any key to exit. ");
string iQuestion = Console.ReadLine();
if (iQuestion.Equals("y", StringComparison.OrdinalIgnoreCase))
{
ProjectExecution();
Console.WriteLine("\nWorld you like to try again?\nPress y to play again\tEnter any key to exit. ");
string ask = Console.ReadLine();
if (ask.Equals("y", StringComparison.OrdinalIgnoreCase))
{
ProjectExecution();
}
else
{
Console.WriteLine("Thank you for playing");
}
Console.Read();
}
else if (iQuestion.Equals("m", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Hwewewe\nPress C to continue");\\This is just an example
string mQuestion = Console.ReadLine();
if (mQuestion.Equals("c", StringComparison.OrdinalIgnoreCase))
{
Console.Clear();
ProjectExecution();
Console.Read();
}
}
else
{
Environment.Exit(10);
}
}
I am open to another solution.
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);
I am looking to get the menu to loop so when I enter the help menu and then return to the main menu it will actually run. Instead it doesn't respond when anything is entered. The exit also does not work for whatever reason and therefore I would appreciate any help given. Thank you.
using System;
namespace MasterMind
{
class Menu
{
public void DrawMainMenu()
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" MasterMind's Main Menu");
Console.WriteLine(" 1: Play");
Console.WriteLine(" 2: Help");
Console.WriteLine(" 0: Exit");
}
public void DrawHelp()
{
Console.Clear();
Console.WriteLine("Rules Of MasterMind!");
Console.WriteLine("Mastermind is a game about guessing a 4 digit code. The numbers can range from");
Console.WriteLine("1-4 and any other numbers will be rejected. It will say in the CMD");
Console.WriteLine("prompt whether or not you had any of the number correct or false.");
Console.WriteLine("Press any key to go back to the main menu.");
Console.ReadKey();
Console.Clear();
DrawMainMenu();
Console.ReadLine();
}
public void DrawExit()
{
Console.Clear();
Console.WriteLine("You are about to exit the game");
Console.WriteLine("Are you sure: Y/N");
string userExit = Console.ReadKey().KeyChar.ToString();
if (userExit == "Y")
{
Environment.Exit(0);
}
if (userExit == "N")
{
DrawMainMenu();
Console.ReadLine();
}
}
}
class Program
{
static void Main(string[] args)
{
var menu = new Menu();
menu.DrawMainMenu();
string userInput = Console.ReadKey().KeyChar.ToString();
if (userInput == "1")
{
}
if (userInput == "2")
{
Console.Clear();
menu.DrawHelp();
}
if (userInput == "0")
{
menu.DrawExit();
Console.ReadLine();
}
}
}
}
Something like this can get you started.
Note: there are improvements you can make to the structure and logic in various ways....I'll just give you one example e.g. having the Environment.Exit(0); where it is could be frowned upon...it could be avoided by having a "flag" on the while loop, which is set if you choose "exit", and then the program just exits naturally.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
using System;
namespace MasterMind
{
class Menu
{
public void DrawMainMenu()
{
Console.Clear();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" MasterMind's Main Menu");
Console.WriteLine(" 1: Play");
Console.WriteLine(" 2: Help");
Console.WriteLine(" 0: Exit");
}
public void DrawHelp()
{
Console.Clear();
Console.WriteLine("Rules Of MasterMind!");
Console.WriteLine("Mastermind is a game about guessing a 4 digit code. The numbers can range from");
Console.WriteLine("1-4 and any other numbers will be rejected. It will say in the CMD");
Console.WriteLine("prompt whether or not you had any of the number correct or false.");
Console.WriteLine("Press any key to go back to the main menu.");
Console.ReadKey();
}
public void DrawExit()
{
Console.Clear();
Console.WriteLine("You are about to exit the game");
Console.WriteLine("Are you sure: Y/N");
string userExit = Console.ReadKey().KeyChar.ToString();
if (userExit.ToUpper() == "Y")
{
Environment.Exit(0);
}
}
}
class Program
{
static void Main(string[] args)
{
var menu = new Menu();
while (true)
{
menu.DrawMainMenu();
string userInput = Console.ReadKey().KeyChar.ToString();
if (userInput == "1")
{
Console.Clear();
Console.WriteLine("Playing...");
Console.ReadKey();
}
if (userInput == "2")
{
menu.DrawHelp();
}
if (userInput == "0")
{
menu.DrawExit();
}
}
}
}
}
}
My c# console application is used as a login for my c# form application, the problem is, in my c# console app i haven't been able to figure out a way to ReadLine without the need of pressing Enter because i need to detect whether F2 or Enter is pressed then ReadLine without needing user to press Enter again. For example, if i wanted to detect if F2 is pressed i would need to wait until F2 is pressed until I'm able to ReadLine, Hopefully this question was worded in a way that it makes sense, I'm sure you can tell I'm quite a 'noob' at c#.
Example of my problem:
static void Main()
{
var KP = Console.ReadKey();
if (KP.Key == ConsoleKey.F2)
{
//User Presses F2
}
else if (KP.Key == ConsoleKey.Enter)
{
string UserName = ReadLineWithoutPressingEnter();//Just a example
//ReadLine without needing to press enter again
}
}
Thank you for your time.
Save the result from ReadKey and then just do a ReadLine:
public static void Main(string[] args)
{
var KP = Console.ReadKey();
if (KP.Key == ConsoleKey.F2)
{
return;
}
string UserName = KP.KeyChar + Console.ReadLine();
Console.WriteLine(UserName);
Console.ReadLine();
}
You've already found Console.ReadKey(). That's a start. You'll need to also build a state machine around this function to return a completed string at the end of the line, but this method is the key to making that work. Don't forget to handle things like backspace and delete.
Here is an example Try this
static void Main(string[] args)
{
ConsoleKeyInfo cki = new ConsoleKeyInfo();
int i = 0;
do
{
while (Console.KeyAvailable == false)
Thread.Sleep(250); // Loop until input is entered.
cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.F1)
{
Console.WriteLine("User Have Press F1");
//do some thing
}
if (cki.Key == ConsoleKey.Enter)
{
Console.WriteLine("User Have Press Enter");
//do some thing
}
if (cki.Key == ConsoleKey.A)
{
Console.WriteLine("User Have Press A");
//do some thing
}
} while (cki.Key != ConsoleKey.X);
}
This should work
static void Main(string[] args)
{
ConsoleKeyInfo e;
string userName = "";
while (true)
{
e = Console.ReadKey();
if (e.Key == ConsoleKey.Enter)
{
break;
}
else if (e.Key == ConsoleKey.F2)
{
//things to do when F2
}
userName += e.KeyChar;
}
Console.WriteLine("username: " + userName);
Console.Read();
}
This is a simple begginer program with setter and getter concept
now i have to make it to first enter user name and password to get welcomed
and IF I ENTER WRONG INFO IT SHOULD DISPLAY INVALID AND 5 TRIES LEFT THEN if i again enter wrong info it should display 4 tries left and so on and finally when all tries are over it should hang the program or lock the screen or so
using System;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
}
else
{
Console.Clear();
Console.WriteLine("Invalid");
Console.WriteLine("\n \n \n To try again enter y");
int n = 5;
string yes = Console.ReadLine();
if (yes == "y")
{
while (n >= 1)
{
Console.Write(n + " Tries left");
goto label1;
n = --n;
}
}
}
Console.ReadKey();
}
}
class demo
{
private string name, pass;
public void setName(string name)
{
this.name = name;
}
public string getName()
{
return name;
}
public void setPass(string pass)
{
this.pass = pass;
}
public string getPass()
{
return pass;
}
}
}
Please suggest a simple begginers code to make the loop work and make the count down
A while loop should suffice. Using a boolean to detect successful password entry.
When entered, it will break out of the loop.
invalid attempts will decrement the AttemptsLeft int.
Note: I haven't tried this in Visual Studio, the logic should be sound, but I recommend debugging and stepping through it to test if it meets your criteria.
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
bool SuccessfulPassword = false;
int AttemptsLeft = 5;
while(!SuccessfulPassword && AttemptsLeft > 0){
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
SuccessfulPassword = true;
}
}
else
{
AttemptsLeft--;
Console.Clear();
Console.WriteLine("Invalid");
Console.WriteLine("\n \n \n To try again enter y");
int n = 5;
string yes = Console.ReadLine();
if (yes == "y")
{
Console.Write(AttemptsLeft + " Tries left");
}
}
Console.ReadKey();
}
}
try this updated main method:
static void Main(string[] args)
{
demo obj = new demo();
int n = 5;
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
//Console.Clear();
label1:
Console.WriteLine("\n");
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit" && obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
else
{
//Console.Clear();
if (n < 1)
{
//Add ur screenlock n hang prog code
Console.Clear();
Console.WriteLine("ScreenLock");
}
else
{
Console.WriteLine("\n Invalid");
Console.WriteLine("\n To try again enter y");
string yes = Console.ReadLine();
Console.WriteLine("\n");
if (yes == "y")
{
while (n >= 1)
{
Console.Write(n + " Tries left");
n = --n;
goto label1;
}
}
}
}
Console.ReadKey();
}
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
boolean successful = false;
int32 tries = 5;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Do
{
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
successful = true;
}
}
if (!successful)
{
tries--;
Console.Clear();
Console.WriteLine("Invalid");
if (tries > 1)
{
Console.WriteLine("Have " + tries + " attempts left");
}
ElseIf (tries == 1)
{
Console.WriteLine("Have only one more attempt left");
}
Else
{
Console.WriteLine("Maximum number of tries exceed");
Console.WriteLine("Goodbye");
}
}
} While(!successful && Tries > 0);
}
}
Everytime you get the wrong input, you remaking your count int n = 5;
so everytime you have 5 tries left.
What you can do is to declare your count outside of the static void Main(string args[]) method
just like:
int n =5;
static void Main(string args[])
{
}
you problems are the following nested if-contitions
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
}
else
{
\\...
}
If the username is correct and the pass not, it wont enter the else branch.
a better solution to ask for input until it is valid id a do ... while loop
Following example has a lot of improvements over yours.
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
int maxTries;
int tries = maxTries = 5;
do
{
if (tries != maxTries)//second and more
{
Console.Clear();
Console.WriteLine("Invalid");
Console.Write("\n\t" + tries + " Tries left");
Console.WriteLine("\n\n\n\tTry again? (y/n)");
string input;
do
{
input = Console.ReadLine();
} while (input != "y" && input != "n");
if (input == "n")
{
return; // exit the program
}
}
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
tries--;
} while (obj.getName() != "niit" || obj.getPass() != "1234");
Console.WriteLine("Wellcome");
}
PS: Classes should start with a capital letter.
goto is a relict of old times, it will mess with your programm structure and make things more complicated than they are. The only propper use i know is for fallthrough in switches, which also is needed only in rare cases.
A madeup one would be:
string vehicleType = "car";
switch(vehicleType)
{
case "truck":
Console.WriteLine("two wheeles and");
goto case "car";
case "car":
Console.WriteLine("two wheeles and");
goto case "motor cycle";
case "motor cycle":
Console.WriteLine("two wheeles");
break;
case "boat":
Console.WriteLine("no wheeles");
break;
}