Console application, How do I make Console.ReadLine() IF/ELSE Statements? [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I was making a tool named "Ferna".. And I was trying to make different commands on it, but the problem is that these "commands" have to be in order, like when I try to execute a command, I have to execute them in order.. But I want it like it doesn't have to be in order so if i write "cyan" it executes it, it doesn't have to wait for the 5th ReadLine()
Here's my code:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
if (Console.ReadLine() == "cmds")
{
Console.WriteLine(cmds);
}
else if (Console.ReadLine() == "calculator")
{
cal.ShowDialog();
}
else if (Console.ReadLine() == "cyan")
{
Console.ForegroundColor = ConsoleColor.Cyan;
}
else if (Console.ReadLine() == "black")
{
Console.ForegroundColor = ConsoleColor.Black;
}
else if (Console.ReadLine() == "clear")
{
Console.Clear();
}
}
}
}

Store the results of your Console.ReadLine statement in a variable. This way you don't have to keep calling Console.ReadLine.
var cmd = Console.ReadLine();
if (cmd == "cmds")
{
Console.WriteLine(cmds);
}
else if (cmd == "calculator")
{
...
The issue is essentially every time the if checks each condition its going to wait for more input
Update :
You will need to put it in a loop
string cmd = "";
while(cmd != "exit")
{
cmd = Console.ReadLine();
if (cmd == "cmds")
{
Console.WriteLine(cmds);
}
else if (cmd == "calculator")
{
...
}

Here is the good old switch statement. Gotta break it out every once in while! If/Else works just as well though. This will loop and check for the next line.
class Program
{
static void Main(string[] args)
{
while((string command = Console.ReadLine()) != null)
{
switch (command.ToUpper())
{
case "CMD":
Console.WriteLine("CMD");
break;
case "CALCULATOR":
cal.ShowDialog();
break;
default:
Console.WriteLine("Default");
break;
}
}
}
}

Using Queue<string> to keep a list of commands might not be a bad idea:
class Program
{
static Queue<string> commandQueue = new Queue<string>(new[] {"FirstCommand", "SecondCommand", "ThirdCommand"});
static void Main(string[] args)
{
using (Queue<string>.Enumerator enumerator = commandQueue.GetEnumerator())
{
while (enumerator.MoveNext())
{
Console.WriteLine("Type in next command or type exit to close application");
//this while is used to let user make as many mistakes as he/she wants.
while (true)
{
string command = Console.ReadLine();
if (command == "exit")
{
Environment.Exit(0);
}
//if typed command equals current command in queue ExecuteCommand and move queue to next one
if (command == enumerator.Current)
{
ExecuteCommand(command);
break;
}
else//Show error message
{
if (commandQueue.Contains(command))
{
Console.WriteLine("Wrong command.");
}
else
{
Console.WriteLine("Command not found.");
}
}
}
}
Console.WriteLine("We are done here, press enter to exit.");
Console.ReadLine();
}
}
//Method that executes command according to its name
static void ExecuteCommand(string commandName)
{
switch (commandName)
{
case "FirstCommand":
Console.WriteLine("FirstCommand executed");
break;
case "SecondCommand":
Console.WriteLine("SecondCommand executed");
break;
case "ThirdCommand":
Console.WriteLine("ThirdCommand executed");
break;
default:
Console.WriteLine("Command not found");
break;
}
}
}
Also if the requirement states that actions should performed in exact order it might not be a bad idea to just let the user press Enter to execute the next command instead of having to type its name.

Related

How to remove the input string from the list? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Here is my code.The first and third points of the program work properly, but the second does not.
If you press the "2" key, the data from the text should be transferred to the list, and the entered line should be deleted in the list,but for reasons I do not understand, the program crashes when entering a value into a string.
using System;
using System.IO;
using System.Collections;
using System.Linq;
using System.Text;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
String line;
List<String> list = new List<String>();
String writePath = #"C:\Work\X\hta.txt";
for (; ; )
{
Console.WriteLine("1.Add An Employee");
Console.WriteLine("2.Delete An Employee");
Console.WriteLine("3.Save Database");
Console.WriteLine("4.Exit");
int choice = Convert.ToInt32(Console.ReadLine());
if (choice == 4)
{
break;
}
switch (choice)
{
case 1:
for (; ; )
{
Console.WriteLine("1.Add A Manager");
Console.WriteLine("2.Add An Engineer");
Console.WriteLine("3.Exit");
int choice1 = Convert.ToInt32(Console.ReadLine());
if (choice1 == 3)
{
break;
}
switch (choice)
{
case 1:
line = Console.ReadLine();
list.Add(line);
break;
case 2:
line = Console.ReadLine();
list.Add(line);
break;
}
}
break;
case 2:
list.Clear();
using (StreamReader sr = new StreamReader(writePath))
{
while (!sr.EndOfStream)
{
list.Add(sr.ReadLine());
}
}
foreach(var item1 in list)
{
String linex = Console.ReadLine();
if (item1.Equals(linex))
{
list.Remove(linex);
}
}
break;
case 3:
Console.WriteLine("Do you want to continue?");
String x = Console.ReadLine();
if (x.Equals("yes")){
using (StreamWriter sw = new StreamWriter(writePath))
{
foreach (var item in list)
{
sw.WriteLine(item);
}
}
}
else
{
break;
}
break;
}
Console.ReadLine();
}
}
}
}
In this loop:
foreach(var item1 in list)
{
String linex = Console.ReadLine();
if (item1.Equals(linex))
{
list.Remove(linex);
}
}
You are reading input from the console for every item in the list. This would possibly look like a crash or not quite infinite loop as it's probably not what you're expecting. Instead you should read the input once then loop around the list. However, you should note that if you remove an item from the list while looping through it, you may also get strange behavior. Try just removing the string without the loop:
String linex = Console.ReadLine();
if (list.Contains(linex))
{
list.Remove(linex);
}
may be you writePath of value [C:\Work\X\hta.txt] file do not exists,so you should create an empty text file on you disk.

How do you execute a method only if another one has been run?

I have a choice for the user in Main using a switch. Depending on what the user chooses, several choices later, the program will either end or not. At least, that is what I'm trying to accomplish.
//This is in Main
string[] menyVal2 = new string[] {"Go to the hotel room", "Go to the dining hall"};
string title2 = "text";
int choice2 = menu(menuChoice2, title2);
switch (choice2)
{
case 0:
hotelRoom();
break;
case 1:
diningHall();
break;
}
Many lines of code later...
public static void save()
{
Console.Clear();
string[] menuChoice = {"Chapter 2", "Back to start"};
string title = "text";
int choice = menu(menuChoice, title);
switch (val)
{
case 0:
if (hotelRoom = true) //this if-statement does not work
{
withoutCross();
}
else if (diningHall = true)
{
withCross();
}
break;
case 1:
Main(new string[] { });
break;
}
}
When I understand your title of the question correctly, then this is a solution:
Make the return type of the method bool and fill it to a variable.
bool isMethodExecuted = MyMethod();
Later you can check with a if-Statement, if the method is executed:
if(isMethodExecuted)
MyOtherMethod();

How can I escape from this loop?

I am a beginner at coding - I just started a week ago. I am trying to develop a program where the user can either see all of the names in a list or add a name to a list. When the user prompts to see the names in the list, and then decides to take another action, they are stuck in an endless loop where they can only see the names again. I want them to be able to go back to the start and choose to either see the names or add a name.
I've tried reorganizing and looking things up, but I'm still at a loss.
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> names = new List<string>();
names.Add("Vasti");
names.Add("Cameron");
names.Add("Ezra");
names.Add("Tilly");
bool program = false;
bool program2 = false;
Console.WriteLine("Welcome to the names lost! If you wish to add
a name to the list, type 1. If you want to see current names in
the list,
type 2.");
string userChoice = Console.ReadLine();
do
{
switch (userChoice)
{
case "1":
Console.WriteLine("Add a name to the squad.");
string userAddName = Console.ReadLine();
names.Add(userAddName);
break;
case "2":
Console.WriteLine("Here's the list:");
foreach (string name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("Wanna do that again? Type yes or
no.");
do
{
string userContinue = Console.ReadLine();
switch (userContinue)
{
case "yes":
program = true;
program2 = false;
break;
case "Yes":
program = true;
program2 = false;
break;
case "no":
program = false;
program2 = false;
break;
case "No":
program = false;
program2 = false;
break;
default:
Console.WriteLine("Please enter either
yes or no");
userContinue = Console.ReadLine();
program2 = true;
break;
}
}
while (program2 == true);
break;
default:
Console.WriteLine("Please type either 1 or 2 to
select an option.");
break;
}
}
while (program == true);
}
}
I expect the user to return to the beginning prompt, but they are stuck in the same prompt over and over. There are no error messages.
Two major things to cover your difficulties.
First, the input hint should be in the loop so it can show when each loop begin.
Second, do while loop decide if the loop should continue at the end and in your design; it depends on what user input which should be directly utilized as while condition.
Therefore, your code could be simplified as
public static void Main()
{
List<string> names = new List<string>() { "Vasti", "Cameron", "Ezra", "Tilly" };
string userChoice = "";
do
{
Console.WriteLine($#"Welcome to the names lost!{Environment.NewLine} If you wish to add a name to the list, type 1.{Environment.NewLine} If you want to see current names in the list, type 2.");
userChoice = Console.ReadLine();
switch (userChoice)
{
case "1":
Console.WriteLine("Add a name to the squad.");
string userAddName = Console.ReadLine();
names.Add(userAddName);
break;
case "2":
Console.WriteLine("Here's the list:");
foreach (string name in names)
{
Console.WriteLine(name);
}
break;
default:
Console.WriteLine("Please type either 1 or 2 to select an option.");
break;
}
Console.WriteLine(#"Wanna do that again? Type yes or no.");
userChoice = Console.ReadLine();
}
while (userChoice.Equals("yes", StringComparison.OrdinalIgnoreCase));
Console.WriteLine("Program finished");
Console.ReadLine();
}
Change the do{}while() loops to regular while(){} loops.Move string userChoice = Cosole.ReadLine(); inside of the top while loop or you will never ask for other options. . . Also set the ((bool program=true; and bool program=true;)) at the beginning. Do{}while() loops do everything inside the {} first then check to see if the while statement is still true.

The name 'input' does not exist in the current context

I've been C# programming for about a year now and I normally get into problems like this by overlooking a detail somewhere. I feel like I am doing this again but I can't seem to solve the problem. I have a string variable named 'input' I have declared it in an 'if' statement in my 'Main' class like so:
string input = Console.Readline();
As a separate 'if' statement, in the same 'Main' class, I have written this:
if (input != null || input != 0)
{
//I have code for this part, but it is irrelevant
}
else
{
//And this part, but it is also irrelevant
}
my problem is that MonoDevelop is highlighting both of the 'input' variables in the second 'if' statement and saying 'the name input does not exist in the current context'. I feel like I am overlooking something, any help would be appreciated.
My full code is this:
using System;
namespace ConsoleTest
{
class MainClass
{
public static string version = "0.0.1";
public static string precursor = "/:>";
public static void Main (string[] args)
{
Console.Write ("Console Test ");
Console.WriteLine (version);
Console.Write (precursor);
string start = Console.ReadLine ();
if (start == "start") {
while (true) {
Console.WriteLine ("Started");
Console.Write (precursor);
string input = Console.ReadLine ();
}
} else {
Environment.Exit (0);
}
if (input != null || input != 0) {
//Code
} else {
Console.WriteLine("Error: Input null");
}
}
}
}
Declare your input variable before your first if statement. Because it is declared inside it is only available inside your if statement (or in this case inside your loop)
input exists only in the scope of your while loop inside your first if statement.
Move it outside.
string input = new string();
if (start == "start") {
while (true)
{
Console.WriteLine ("Started");
Console.Write (precursor);
input = Console.ReadLine ();
}
}
More code is needed, however it may be because you are trying to compare a String to an int. Perhaps you were looking for
input.equals("0")?
Edit: Looking at your code, you initialized the variable in the if statement. You have to initialize it at the beginning of your function. Even if you just set it to null.
public static void Main (string[] args)
{
Console.Write ("Console Test ");
Console.WriteLine (version);
Console.Write (precursor);
string start = Console.ReadLine ();
string input = null;
if (start == "start") {
while (true) {
Console.WriteLine ("Started");
Console.Write (precursor);
input = Console.ReadLine ();
}
} else {
Environment.Exit (0);
}
if (input != null || !input.equals("0")) {
//Code
} else {
Console.WriteLine("Error: Input null");
}
}
Your string input is declared inside your loop. Therefor, it isn't known after this loop.
Declare it outside your loop (and initiate it to null or String.Empty) then fill it inside your loop

'Advanced' Console Application

I'm not sure if this question has been answered elsewhere and I can't seem to find anything through google that isn't a "Hello World" example... I'm coding in C# .NET 4.0.
I'm trying to develop a console application that will open, display text, and then wait for the user to input commands, where the commands will run particular business logic.
For example: If the user opens the application and types "help", I want to display a number of statements etc etc. I'm not sure how to code the 'event handler' for user input though.
Hopefully this makes sense. Any help would be much appreciated!
Cheers.
You need several steps to achieve this but it shouldn't be that hard. First you need some kind of parser that parses what you write. To read each command just use var command = Console.ReadLine(), and then parse that line. And execute the command... Main logic should have a base looking this (sort of):
public static void Main(string[] args)
{
var exit = false;
while(exit == false)
{
Console.WriteLine();
Console.WriteLine("Enter command (help to display help): ");
var command = Parser.Parse(Console.ReadLine());
exit = command.Execute();
}
}
Sort of, you could probably change that to be more complicated.
The code for the Parser and command is sort of straight forward:
public interface ICommand
{
bool Execute();
}
public class ExitCommand : ICommand
{
public bool Execute()
{
return true;
}
}
public static Class Parser
{
public static ICommand Parse(string commandString) {
// Parse your string and create Command object
var commandParts = commandString.Split(' ').ToList();
var commandName = commandParts[0];
var args = commandParts.Skip(1).ToList(); // the arguments is after the command
switch(commandName)
{
// Create command based on CommandName (and maybe arguments)
case "exit": return new ExitCommand();
.
.
.
.
}
}
}
I know this is an old question, but I was searching for an answer too. I was unable to find a simple one though, so I built InteractivePrompt. It's available as a NuGet Package and you can easily extend the code which is on GitHub. It features a history for the current session also.
The functionality in the question could be implemented this way with InteractivePrompt:
static string Help(string strCmd)
{
// ... logic
return "Help text";
}
static string OtherMethod(string strCmd)
{
// ... more logic
return "Other method";
}
static void Main(string[] args)
{
var prompt = "> ";
var startupMsg = "BizLogic Interpreter";
InteractivePrompt.Run(
((strCmd, listCmd) =>
{
string result;
switch (strCmd.ToLower())
{
case "help":
result = Help(strCmd);
break;
case "othermethod":
result = OtherMethod(strCmd);
break;
default:
result = "I'm sorry, I don't recognize that command.";
break;
}
return result + Environment.NewLine;
}), prompt, startupMsg);
}
This is easy enough, just use the Console.WriteLine and Console.ReadLine() methods. From the ReadLine you get a string. You could have a horrible if statement that validate this against known/expected inputs. Better would be to have a lookup table. Most sophisticated would be to write a parser. It really depends on how complex the inputs can be.
Console.WriteLine Console.ReadLine and Console.ReadKey are your friends. ReadLine and ReadKey waits for user input. The string[] args will have all of your parameters such as 'help' in them. The array is created by separating the command line arguments by spaces.
switch (Console.ReadLine())
{
case "Help":
// print help
break;
case "Other Command":
// do other command
break;
// etc.
default:
Console.WriteLine("Bad Command");
break;
}
If you're looking to parse commands that have other things in them like parameters, for example "manipulate file.txt" then this alone won't work. But you could for example use String.Split to separate the input into a command and arguments.
A sample:
static void Main(string[] args)
{
Console.WriteLine("Welcome to test console app, type help to get some help!");
while (true)
{
string input = Console.ReadLine();
int commandEndIndex = input.IndexOf(' ');
string command = string.Empty;
string commandParameters = string.Empty;
if (commandEndIndex > -1)
{
command = input.Substring(0, commandEndIndex);
commandParameters = input.Substring(commandEndIndex + 1, input.Length - commandEndIndex - 1);
}
else
{
command = input;
}
command = command.ToUpper();
switch (command)
{
case "EXIT":
{
return;
}
case "HELP":
{
Console.WriteLine("- enter EXIT to exit this application");
Console.WriteLine("- enter CLS to clear the screen");
Console.WriteLine("- enter FORECOLOR value to change text fore color (sample: FORECOLOR Red) ");
Console.WriteLine("- enter BACKCOLOR value to change text back color (sample: FORECOLOR Green) ");
break;
}
case "CLS":
{
Console.Clear();
break;
}
case "FORECOLOR":
{
try
{
Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), commandParameters);
}
catch
{
Console.WriteLine("!!! Parameter not valid");
}
break;
}
case "BACKCOLOR":
{
try
{
Console.BackgroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), commandParameters);
}
catch
{
Console.WriteLine("!!! Parameter not valid");
}
break;
}
default:
{
Console.WriteLine("!!! Bad command");
break;
}
}
}
}
This is very simplistic, but might meet your needs.
// somewhere to store the input
string userInput="";
// loop until the exit command comes in.
while (userInput != "exit")
{
// display a prompt
Console.Write("> ");
// get the input
userInput = Console.ReadLine().ToLower();
// Branch based on the input
switch (userInput)
{
case "exit":
break;
case "help":
{
DisplayHelp();
break;
}
case "option1":
{
DoOption1();
break;
}
// Give the user every opportunity to invoke your help system :)
default:
{
Console.WriteLine ("\"{0}\" is not a recognized command. Type \"help\" for options.", userInput);
break;
}
}
}
There is a C# nuget package called 'ReadLine' by 'tornerdo'. The statement ReadLine.Read(" prompt > "); prompts the user within options provided in CustomAutoCompletionHandler.PossibleAutoCompleteValues.
Additionally, you can change the CustomAutoCompletionHandler.PossibleAutoCompleteValues for each prompt. This ensures that the user get to choose an option from available\ supported list of options. Less error prone.
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(" Note! When it prompts, press <tab> to get the choices. Additionally, you can use type ahead search.");
Console.ForegroundColor = ConsoleColor.White;
// Register auto completion handler..
ReadLine.AutoCompletionHandler = new CustomAutoCompletionHandler();
CustomAutoCompletionHandler.PossibleAutoCompleteValues = new List<string> { "dev", "qa", "stg", "prd" };
var env = CoverReadLine(ReadLine.Read(" Environment > "));
Console.WriteLine($"Environment: {env}");
}
private static string CoverReadLine(string lineRead) => CustomAutoCompletionHandler.PossibleAutoCompleteValues.Any(x => x == lineRead) ? lineRead : throw new Exception($"InvalidChoice. Reason: No such option, '{lineRead}'");
public class CustomAutoCompletionHandler : IAutoCompleteHandler
{
public static List<string> PossibleAutoCompleteValues = new List<string> { };
// characters to start completion from
public char[] Separators { get; set; } = new char[] { ' ', '.', '/' };
// text - The current text entered in the console
// index - The index of the terminal cursor within {text}
public string[] GetSuggestions(string userText, int index)
{
var possibleValues = PossibleAutoCompleteValues.Where(x => x.StartsWith(userText, StringComparison.InvariantCultureIgnoreCase)).ToList();
if (!possibleValues.Any()) possibleValues.Add("InvalidChoice");
return possibleValues.ToArray();
}
}

Categories