Can a boolean be asked? - c#

So Im new into coding. And my question is, can u make someone type if a question is yes or no and if it its true using, the swith statement say its correct. But I want to make it that the answer can be only yes or no and each bool is true or false. If not what can I do to make this work?
using System;
namespace FliptheIntegerBoolean
{
class Program
{
static void Main(string[] args)
{
bool yes;
bool no;
Console.Write("Is a dog a animal? ");
bool yes = Convert.ToBoolean( Console.ReadLine());
switch (yes)
{
case true:
Console.WriteLine("yes it is");
break;
default:
Console.WriteLine("U dumb?");
break;
}
switch (no)
{
case true:
Console.WriteLine("Then what is it? XDD");
break;
default:
Console.WriteLine("U dumb?");
break;
}
Console.ReadKey();
}
}
}

You can use an if ... else... statement
using System;
namespace FliptheIntegerBoolean {
class Program {
static void Main(string[] args) {
Console.Write("Is a dog an animal? ");
string answer = Console.ReadLine();
if (answer == "yes") {
Console.WriteLine("yes it is");
} else if (answer == "no") {
Console.WriteLine("Then what is it? XDD");
} else {
Console.WriteLine("U dumb?");
}
Console.ReadKey();
}
}
}

If you want need result as Boolean
namespace FliptheIntegerBoolean
{
class Program
{
static void Main(string[] args)
{
bool yes;
while (true)
{
Console.Write("Is a dog a animal? ");
string answer = Console.ReadLine();
if (answer.ToLower() == "yes")
{
yes = true;
}
else if (answer.ToLower() == "no")
{
yes = false;
}
else
{
Console.WriteLine("Then what is it? XDD");
continue;
}
Console.WriteLine(yes ? "yes it is" : "Then what is it? XDD");
}
}
}
}

Related

How to create a counter that counts unrighteous inputs

static void MainWindow()
{
Console.Clear();
Console.WriteLine("Menu");
Console.WriteLine("");
Console.WriteLine("1. Information");
Console.WriteLine("2. Contact");
Console.WriteLine("3. Extra");
Console.WriteLine("q. Exit");
string myOptions;
myOptions = Console.ReadLine();
switch (myOptions)
{
case "1":
Information();
break;
case "2":
Contact();
break;
case "3":
Extra();
break;
case "q":
Exit();
break;
default:
Console.Clear();
Console.WriteLine("Input is wrong");
Console.ReadKey();
MainWindow();
break;
}
Console.ReadLine();
}
I make a console menu and I need a counter that will count wrong entries. if it hits 5 times, the user is thrown back to the main menu.
I was trying to do this with while statement but it didnt work for me.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace ConsoleApp3
{
internal class Program
{
private static readonly IDictionary<char, Action> InputDictionary = new Dictionary<char, Action>
{
{ '1', Information },
{ '2', Contact },
{ '3', Extra },
{ 'q', Exit },
};
static void Main()
{
MainWindow();
}
private static void MainWindow()
{
var inputWasProcessed = false;
while (inputWasProcessed == false)
{
DisplayMainMenu();
var wrongEntries = 0;
while (wrongEntries < 5)
{
if (0 < wrongEntries)
{
Console.WriteLine($"Wrong Entries: {wrongEntries}");
}
inputWasProcessed = ProcessUserInput(Console.ReadKey().KeyChar);
if (inputWasProcessed == false)
{
wrongEntries++;
}
else
{
break;
}
}
}
Console.ReadLine();
}
private static void DisplayMainMenu()
{
Console.Clear();
Console.WriteLine("Menu");
Console.WriteLine();
Console.WriteLine("1. Information");
Console.WriteLine("2. Contact");
Console.WriteLine("3. Extra");
Console.WriteLine("q. Exit");
}
private static bool ProcessUserInput(char selectedOption)
{
if (InputDictionary.TryGetValue(selectedOption, out var action))
{
Console.WriteLine();
Console.WriteLine();
action.Invoke();
return true;
}
Console.Clear();
Console.WriteLine("Input is wrong.");
Console.WriteLine("Try again.");
return false;
}
private static void Information()
{
Console.WriteLine($"{GetCurrentMethod()} implementation.");
}
private static void Contact()
{
Console.WriteLine($"{GetCurrentMethod()} implementation.");
}
private static void Extra()
{
Console.WriteLine($"{GetCurrentMethod()} implementation.");
}
private static void Exit()
{
Console.WriteLine($"{GetCurrentMethod()} implementation.");
}
#region For Demonstration Purposes Only
[MethodImpl(MethodImplOptions.NoInlining)]
private static string GetCurrentMethod() // https://stackoverflow.com/a/2652481/109941
{
var st = new StackTrace();
var sf = st.GetFrame(1);
return sf.GetMethod().Name;
}
#endregion
}
}

While pressing enter key it should display same menu

I am displaying menu in the console based application using C#. I want that if user press enter key then it should display same menu. Application should not break. I am new to C#
If anyone has idea please share it. It will be helpful to me.
Below is the code.
public static void HospitalMenu()
{
string answer = "";
do
{
Console.Clear();
Console.WriteLine("=============Hospital Management System===================");
Console.WriteLine("1...............Add Patient Information");
Console.WriteLine("2...............Modify Patient Information");
Console.WriteLine("3...............Add Patient Treatment Information");
Console.WriteLine("4...............View Patient History");
Console.WriteLine("5...............Search Patient Info");
Console.WriteLine("6...............Generate Lab Report");
Console.WriteLine("7...............Generate Medical Bills");
Console.WriteLine("8...............Exit");
Console.WriteLine("Select option (between 1 to 8)");
int option = Convert.ToInt32(Console.ReadLine());
switch (option)
{
case 1:
Patient.InsertPatient();
break;
case 2:
Patient.UpdatePatient();
break;
case 3:
PatientTreatment();
break;
case 4:
ViewMenu();
break;
case 5:
SearchMenu();
break;
case 6:
LabMenu();
break;
case 7:
BillMenu();
break;
default:
Environment.Exit(0);
break;
}
Console.WriteLine("Do you want to continue ? (Enter y if yes)");
answer = Console.ReadLine();
} while (answer == "y" || answer == "Y");
}
Thanks in advance.
I'll suggest some changes in your code.
Let's create an Interface that you'll be a contract responsible to show and handle inputs
IMenuHandler.cs
public interface IMenuHandler<TInput>
{
void Show( Action stopApplicationHandler, IMenuHandler<TInput> callerMenu=null);
void HandleInput(TInput input, Action stopApplication, IMenuHandler<TInput> callerMenu);
}
Then let's create your menus.. .
As an example you'll create two, you should modify it for your needs.
MainMenu.cs
public class MainMenu:IMenuHandler<ConsoleKeyInfo>
{
public void Show(Action stopApplicationHandler, IMenuHandler<ConsoleKeyInfo> callerMenu = null)
{
Console.Clear();
Console.WriteLine("=============Hospital Management System===================");
Console.WriteLine("1...............Add Patient Information");
Console.WriteLine("2...............Modify Patient Information");
Console.WriteLine("3...............Add Patient Treatment Information");
Console.WriteLine("4...............View Patient History");
Console.WriteLine("5...............Search Patient Info");
Console.WriteLine("6...............Generate Lab Report");
Console.WriteLine("7...............Generate Medical Bills");
Console.WriteLine("8...............Exit");
Console.WriteLine("Select option (between 1 to 8)");
HandleInput(Console.ReadKey(), stopApplicationHandler, callerMenu ?? this);
}
public void HandleInput(ConsoleKeyInfo input, Action stopApplication, IMenuHandler<ConsoleKeyInfo> callerMenu)
{
switch (input.Key)
{
case ConsoleKey.D1:
new HelpMenu().Show(stopApplication, callerMenu);
break;
case ConsoleKey.D8:
stopApplication.Invoke();
break;
default:
Show(stopApplication, this);
break;
}
}
}
HelpMenu.cs
public class HelpMenu:IMenuHandler<ConsoleKeyInfo>
{
public void Show(Action stopApplicationHandler, IMenuHandler<ConsoleKeyInfo> callerMenu = null)
{
Console.Clear();
Console.WriteLine("Help Menu Example...");
Console.WriteLine("1...............Go back");
Console.WriteLine("2...............Exit");
HandleInput(Console.ReadKey(), stopApplicationHandler, callerMenu );
}
public void HandleInput(ConsoleKeyInfo input, Action stopApplication, IMenuHandler<ConsoleKeyInfo> callerMenu)
{
Console.WriteLine("Help menu handler...");
switch (input.Key)
{
case ConsoleKey.D1:
callerMenu.Show(stopApplication, this);
break;
case ConsoleKey.D2:
stopApplication.Invoke();
break;
default:
Show(stopApplication, callerMenu);
break;
}
}
}
Now we are going to create an wrapper for your application.
Application.cs
public class Application
{
public delegate void OnStopApplicationRequestHandler();
public event OnStopApplicationRequestHandler StopApplicationRequest;
private readonly CancellationTokenSource _cancellationTokenSource;
public Application(CancellationToken? cancellationToken=null, OnStopApplicationRequestHandler? stopApplicationRequestHandler=null)
{
_cancellationTokenSource = cancellationToken != null
? CancellationTokenSource.CreateLinkedTokenSource(cancellationToken.Value)
: new CancellationTokenSource();
StopApplicationRequest += stopApplicationRequestHandler ?? ConfigureDefaultStopApplicationRequestHandler();
}
private OnStopApplicationRequestHandler ConfigureDefaultStopApplicationRequestHandler()
=> () =>
{
Console.WriteLine("Stopping application...");
_cancellationTokenSource.Cancel();
};
public void Run()
{
try
{
while (!_cancellationTokenSource.Token.IsCancellationRequested)
new MainMenu().Show(Stop);
Console.WriteLine("Program has been stopped");
}
//.... You should handle other custom exceptions here
catch (Exception ex)
{
// I'll assume that you will stop your application case it hits this unhandled exception
Console.WriteLine(ex);
Stop();
}
}
private void Stop()
{
StopApplicationRequest?.Invoke();
}
}
Note that this class has an event that will be responsible to handle the application exits.
You should modify it for your needs.
Last but not least
Call your application wrapper in your Program.cs
internal class Program
{
static void Main(string[] args)
{
new Application().Run();
}
}
PS: Don't forget the correct usings....
Hope this helps

How to set default capacity for lists

So I tried making a todo list app making use of for loops and nested if statements. I created a function for adding tasks deleting and showing the whole list, but when I run the code I only get to input a task once even though I set the list capacity to what the user wants.
This is my code and what I've tried so far:
namespace mycsharpproject1
{
class Program
{
static void Main(string[] args)
{
List<string> todo = new List<string>();
void addt()
{
Console.WriteLine("enter task to be add");
todo.Add(Console.ReadLine());
}
void removet()
{
Console.WriteLine("enter task to be removed");
todo.Remove(Console.ReadLine());
}
void showt()
{
Console.WriteLine(todo);
}
string user_input = Console.ReadLine();
if (user_input == "r")
{
if (todo.Count == 0)
{
Console.WriteLine("you have no tasks in your list");
}
else
{
removet();
}
}
if (user_input == "a")
{
int i= Convert.ToInt32(Console.ReadLine());
if (i == todo.Capacity)
{
addt();
}
}
if (user_input == "s")
{
showt();
}
Console.ReadKey();
}
}
}
Modified your code a little bit. It's because there's no loop in your code, it only runs once. And the last like Console.ReadKey just reads an input and exits.
And the list doesn't need a capacity to be set if you exactly need that amount of item in yoru list. So, try this one.
class Program
{
static List<string> todo = null;
static void Main(string[] args)
{
todo = new List<string>();
while (true)
{
string user_input = Console.ReadLine();
if (user_input == "r")
{
if (todo.Count == 0)
{
Console.WriteLine("you have no tasks in your list");
}
else
{
removet();
}
}
if (user_input == "a")
{
addt();
}
if (user_input == "s")
{
showt();
}
}
}
static void addt()
{
Console.WriteLine("enter task to be add");
todo.Add(Console.ReadLine());
}
static void removet()
{
Console.WriteLine("enter task to be removed");
todo.Remove(Console.ReadLine());
}
static void showt()
{
todo.ForEach(q => Console.WriteLine(q));
}
}

Accessing list from method in another method

I would like to access list (in my program named "section") inside a method(menu choose). I tried 3 ways:
public static void dataBase()
{
List<float> section = new List<float>();
}
// 1st try
// List<float> section = new List<float>();
//
public static void mainMenu()
{
Console.Clear();
Console.WriteLine("Trans->Connector->\n");
Console.WriteLine("Add: \n1. Section \n2. Wled \n3. Regenerator");
menuChoose();
}
public static void menuChoose()
{
var key = Console.ReadKey();
switch (key.Key)
{
case ConsoleKey.D1:
case ConsoleKey.NumPad1:
Console.Clear();
Console.WriteLine("Give lenght:");
float result;
float.TryParse(Console.ReadLine(), out result);
dataBase.section.Add();
section.Add(result);
break;
case ConsoleKey.D2:
Console.WriteLine("2");
break;
case ConsoleKey.D3:
Console.WriteLine("3");
break;
default:
Console.WriteLine("default");
break;
}
}
static void Main(string[] args)
{
int WeldCount;
int ConnectroCount;
//3rd try
// List<float> section = new List<float>();
//
mainMenu();
}
Thank you for your time!
You can't access a member in the local scope of your function outside it. You might want to think about making it a private instance variable inside your class that you will then be able to access from any method declared that belongs to this class, something along these lines:
public class MyClass
{
// this field is accessible from any method declared within this class
private List<Float> section;
public MyClass()
{
section = new List<Float>();
}
private void someMethod()
{
section.Add(2.2);
Console.WriteLine(section[0]); // example
}
}
Well you can make it class level variable (like in your 1st try) and make it static.
However you should use return value from your menuChoose() method. Having all code depend on single static list instance is not ideal.
public static List<float> menuChoose()
{
List<float> selection = new List<float>();
var key = Console.ReadKey();
switch (key.Key)
{
case ConsoleKey.D1:
case ConsoleKey.NumPad1:
Console.Clear();
Console.WriteLine("Give lenght:");
float result;
float.TryParse(Console.ReadLine(), out result);
selection.Add(result);
break;
case ConsoleKey.D2:
Console.WriteLine("2");
break;
case ConsoleKey.D3:
Console.WriteLine("3");
break;
default:
Console.WriteLine("default");
break;
}
return selection;
}
You can to it, if you would implement something like this:
public static class DataBase
{
public static List<float> Section { get; set; }
static DataBase()
{
Section = new List<float>();
}
}
here how to use e.g. in your switch statement:
case ConsoleKey.NumPad1:
Console.Clear();
Console.WriteLine("Give lenght:");
float result;
float.TryParse(Console.ReadLine(), out result);
DataBase.Section.Add(result);
break;
I didn't get what you try to achieve by dataBase.section.Add(); so I removed it in my example.
I could not use any of your answers so I did this in my way(much worse than yours, for sure)
public class Program
{
public int WeldCount;
public int ConnectroCount;
public List<float> section = new List<float>();
//public List<> TrackElements = new List<>();
public Program()
{
section.Add(0);
}
public void showResults()
{
float allSections = 0;
foreach (float item in section)
{
allSections += item;
}
Console.Clear();
Console.WriteLine("c1 {0}, c2 {1}, c3{2}", WeldCount,ConnectroCount,allSections);
Console.ReadKey();
}
public void finalConstruction()
{
}
public static void mainMenu()
{
Console.Clear();
Console.WriteLine("\n");
Console.WriteLine("Add: \n1. Section \n2. Weld \n3. Regenerator\n4. Show results");
}
public void menuChoose()
{
var key = Console.ReadKey();
switch (key.Key)
{
case ConsoleKey.D1:
case ConsoleKey.NumPad1:
Console.Clear();
Console.WriteLine("Give lenght:");
float result;
float.TryParse(Console.ReadLine(), out result);
section.Add(result);
mainMenu();
menuChoose();
break;
case ConsoleKey.D2:
WeldCount++;
mainMenu();
menuChoose();
break;
case ConsoleKey.D3:
ConnectroCount++;
mainMenu();
menuChoose();
break;
case ConsoleKey.D4:
showResults();
mainMenu();
menuChoose();
break;
default:
Console.WriteLine("wtf did just happend");
break;
}
}
static void Main(string[] args)
{
Program program = new Program();
mainMenu();
program.menuChoose();
}
}
}

Gmail console App C#

I'm trying to figure out why I am getting the error "Cannot assign to 'loggedIn' because it is a method group" within my menu method. Any help will be appreciated. Code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GmailClient
{
class Program
{
static string userName="";
static string passWord="";
public static bool loggedIn()
{
if (userName == "")
{
if (passWord == "")
{
return false;
}
else
{
return false;
}
}
else
{
return true;
}
}
static void Main(string[] args)
{
}
public static void menu()
{
Console.WriteLine("Loading menu.");
if ( loggedIn = false)
{
Console.WriteLine("__________Menu__________");
Console.WriteLine("1) Enter your Gmail credentials");
Console.WriteLine("2) Exit the Console");
Console.WriteLine("________________________");
Console.WriteLine("What do you want to do?");
int userchoice = Convert.ToInt32(Console.ReadLine());
if (userchoice == 1)
{
credentials();
}
else if (userchoice == 2)
{
Console.WriteLine("Hope to see you soon!");
Console.ReadKey();
Environment.Exit(0);
}
}
else if (loggedIn = true)
{
Console.WriteLine("__________Menu__________");
Console.WriteLine("1) Enter your Gmail credentials");
Console.WriteLine("2) Check your inbox");
Console.WriteLine("3) Send an e-mail");
Console.WriteLine("4) Exit the Console");
Console.WriteLine("________________________");
Console.WriteLine("What do you want to do?");
int userchoice = Convert.ToInt32(Console.ReadLine());
if (userchoice == 1)
{
credentials();
}
else if (userchoice ==2)
{
getMail();
}
else if (userchoice ==3)
{
sendMail();
}
else if (userchoice ==4)
{
Console.WriteLine("Hope to see you soon!");
Console.ReadKey();
Environment.Exit(0);
}
}
}
public static void credentials()
{
Console.WriteLine("Enter your Gmail address:");
userName = Console.ReadLine();
Console.WriteLine("Enter your Gmail password:");
passWord = Console.ReadLine();
}
public static void getMail()
{
Console.WriteLine("Loading inbox messages");
}
public static void sendMail()
{
Console.WriteLine("Under Construction");
}
}
}
Change if ( loggedIn = false) to if (!loggedIn()) and if (loggedIn = true) to if (loggedIn()).
Also, when using an if condition check, don't use a single equals =. = is assignment (e.g., You are assigning a value to a variable variable = "value"). Use double equals == when comparing (e.g., if (variable == true) ...).
In the case of your code, loggedIn is defined as a method/function. Your code was treating it as a property/variable.

Categories

Resources