C# Case Statement And Linking To Other Classes, advice needed - c#

have a menu and submenu system, this submenu contains information about locating a driver's location, I want to be able to do a search within the if statement to find out where said Driver is located. I've attached a link to a screenshot if that helps.
http://imageshack.us/f/14/helpub.png/
I want to be able to press the number 1 (or any other number) and for the application to say the following instead of defaulting back to the depot menu:
Please enter name of driver (in this case Steven)
Then for the application to say:
"Steven is located at Depot A"
Any ideas, tips or suggestions greatly appreciated.
I don't want the coding done for me as this is cheating, I just want a pointing in the right direction
Rafa
Apologies, my first post. Okay what I want to happen is that when I press one in the screen the app will ask me to enter driver's name, driver's name is Kenny. Then I want the app to display "Kenny is located at Depot Liverpool" But I'm not sure how to do this.
Code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Sys
{
private bool isLoggedIn = false;
private List<Depot> myDepots;
public Sys()
{
myDepots = new List<Depot>();
// Hard Code Data
myDepots.Add(new Depot("Liverpool"));
myDepots.Add(new Depot("Saint Helens"));
// Hard Code Data
myDepots[0].AddDriver(new Driver("Kenny", "07"));
myDepots[0].AddDriver(new Driver("Steven", "08"));
myDepots[1].AddDriver(new Driver("Jamie", "23"));
myDepots[1].AddDriver(new Driver("Pepe", "25"));
}
public void Run()
{
do
{
Console.WriteLine("Pick Depot");
for (int index = 0; index < myDepots.Count; index++)
{
Console.WriteLine((index + 1).ToString() + " : " + myDepots[index].GetDepotName());
}
int userChoice = Convert.ToInt32(Console.ReadLine());
string userName = "", passWord = "";
if ((userChoice > 0) && (userChoice < 3))
{
Console.Write("Specify UserName : ");
userName = Console.ReadLine();
Console.Write("Specify PassWord : ");
passWord = Console.ReadLine();
bool diditWork = myDepots[userChoice - 1].CheckPassword(userName, passWord);
if (diditWork)
{
Console.WriteLine("We are Logged On!");
Console.WriteLine(myDepots[userChoice - 1].GetMenu());
string menuInput;
int menuInt;
Console.Write("Please select a menu option: \n1 - Locate a Vehicle \n2 - Locate a Driver \n3 - Set up a Work Schedule \n4 - Exit Menu \n");
menuInput = Console.ReadLine();
menuInt = Int32.Parse(menuInput);
if (menuInt < 0)
{
Console.WriteLine("Your menu selection is invalid, please try again", menuInt);
break;
}
if (menuInt == 1)
{
Console.WriteLine("Please enter model name of vehicle", menuInt);
}
if (menuInt == 2)
{
Console.WriteLine("Please enter driver's surname", menuInt);
This is where I need the option to search a driver by name and then have their location reported back to the user of the app. Basically I need the app to say Kenny is located at Depot A
}
if (menuInt == 3)
{
Console.WriteLine("Please assign driver and vehcile to a new work schedule", menuInt);
}
if (menuInt > 4)
{
Console.WriteLine("Your menu selection is invalid, please try again", menuInt);
}
}
else
{
Console.WriteLine("We are Logged Off!");
}
}
isLoggedIn= false;
} while (true);
}
}
}

Well you can use a case statement with what you have and put whatever code you want in there, though most of us would get upset if it was more than five statements...
Looking at your probable intent though.
I think you want a "Task" class.
e.g.
switch(menuInt)
{
case 1 : Console.WriteLine(GetModelName); break;
case 2 : break; //etc
}
If you want to get a bit more clever, define an interface that defines all the things that a menu option must do to intercat with your menu code. Write a class to do what you want, that implements the interface, then use a factory.
Console.Writeline(MenuItemFactory.CreateItem(menuInt).Response);
Maybe, hard to tell this early on. In fact may be it's a bit too early to start refactoring and you should just beaver away with at least a couple of the options before setting anything in stone.

Related

Looping a password checker in C#?

I'm trying to create a password checker.
My idea was to have a bool return type method with a string parameter which would be the user's input. If the string fulfills all the conditions, the method would return true. Otherwise it should return false and loop from the start (take another input from the user to check the password again).
Problem is, even though I got all the conditions that I wanted to have right, I can't get it to loop every time a condition is false. I've tried to do it with for, etc., but it doesn't seem to work. I assume the problem is in the user input (I'm either putting it somewhere that's wrong or something like that) but at this point I'm out of ideas.
If you have an answer, please explain it to me instead of just giving me some code so I can understand where did I go wrong.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BeginnerProjects
{
class PasswordCreator
{
static void Main(string[] args)
{
string passLengthReq = "Password length should be 8 symbols or more.";
string passUppercaseReq = "Password should contain at least one uppercase letter.";
string passDigitReq = "Password should contain at least one digit.";
Console.WriteLine("Please insert your desired password, the password has the following requirements:");
Console.WriteLine($"{passLengthReq}\n{passUppercaseReq}\n{passDigitReq}");
string chosenPass = Console.ReadLine();
do
{
IsPassCorrect(chosenPass);
Console.ReadLine();
}
while (IsPassCorrect(chosenPass) == false);
static bool IsPassCorrect(string chosenPass)
{
// Checks for Null
if (string.IsNullOrEmpty(chosenPass))
{
Console.WriteLine("Password is empty!");
return false;
}
// Checks for Length
else if (chosenPass.Length < 8)
{
Console.WriteLine($"Your password is too short, it contains {chosenPass.Length} characters!");
return false;
}
// Checks for Number Present
else if (!chosenPass.Any(char.IsNumber))
{
Console.WriteLine("Error, your password doesn't contain a number!");
return false;
}
// Checks for Decimal Present
else if (chosenPass.Any(char.IsDigit))
{
Console.WriteLine("Error, your password contains a decimal!");
return false;
}
// Checks for Uppercase Letter
else if (!chosenPass.Any(char.IsUpper))
{
Console.WriteLine("Error, your password doesn't contain an uppercase letter!");
return false;
}
else
{
Console.WriteLine("Your password is valid!");
return true;
}
}
}
}
}
Take this part:
string chosenPass = Console.ReadLine();
do
{
IsPassCorrect(chosenPass);
Console.ReadLine();
}
while (IsPassCorrect(chosenPass) == false);
And change it to:
string chosenPass;
do
{
chosenPass = Console.ReadLine();
}
while (IsPassCorrect(chosenPass) == false);
Now the loop will always prompt the user before checking the password, and keep doing so until IsPassCorrect(chosenPass) returns true.
You can simplify IsPassCorrect(chosenPass) == false if desired:
string chosenPass;
do
{
chosenPass = Console.ReadLine();
}
while (!IsPassCorrect(chosenPass));

Program exiting when using String.ToUpper(); on a string that has spaces in it

Let me start off saying that I'm new to C#.
I'm currently in the making of my first command-line application that in it's current state can do two things. One of them is a calculator, for which I need more learning to actually make it work, and the other is a string capitalizer.
I have a string nameCapInput = Console.Readline() that takes in the user input, which then gets analyzed to make sure that no digits are allowed:
using System;
using System.Linq;
namespace First_Console_Project
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("My first ever console application - 2020/2/26\n\n\n");
programSel:
Console.WriteLine("What do you want to do?\n");
Console.WriteLine("1. Calculate Numbers \n2. Capitalize Letters/Strings");
Console.WriteLine("Input your desired action:");
var inputVar = Console.ReadLine();
switch (inputVar)
{
case "1":
//Calculator code goes here
Console.WriteLine("Number 1 succeeded, opening calculator... Stand by");
Console.WriteLine("Calulator Loaded.");
Console.WriteLine("Doesn't work right now. Type \"exit\" to get back to the \"what do you want to do\" page.");
//Code goes here when I have learned the proper methods
calcInput:
var calcInput = Console.ReadLine();
if (calcInput == "exit")
{
goto programSel;
} else
{
Console.WriteLine("Unknown command. Type \"exit\" to get back to the \"what do you want to do\" page.");
goto calcInput;
}
case "2":
Console.WriteLine("Loading string capitalizer...");
Console.WriteLine("Type any string made of letters only without spaces, because if you use spaces, the program will exit. The output will make them all uppercase. Type \"exit\" to get back to the \"what do you want to do\" page.");
inputCap:
string nameCapInput = Console.ReadLine();
bool containsInt = nameCapInput.Any(char.IsDigit);
bool isMadeOfLettersOnly = nameCapInput.All(char.IsLetter);
if (nameCapInput == "exit")
{
goto programSel;
}
else if (containsInt)
{
Console.WriteLine("You can't capitalize numbers. Use letters only. Try again.");
goto inputCap;
}
else if (isMadeOfLettersOnly)
{
string upper = nameCapInput.ToUpper();
Console.WriteLine($"The uppercase version of your entered text is: {upper}");
goto inputCap;
}
break;
}
}
}
}
Now, everything works fine and it capializes everything I put into it except strings with spaces in them. When I type in a string with spaces in it, the program just exits with code 0. I'm not very good at C# yet, so I don't really know where to go from here. Any help is appreciated.
Every time I learn something new in C#, I try to implement it into my projects, so I can actually learn how to implement it to know when and how to use what I learned. This is an example for that.
EDIT: Added the rest of the code.
Thank you all very much. There's two things I have learned here:
goto is a bad habit
I absolutely need to start learning to debug my own code.
The crux of your problem is that you are only checking if the input contains letters (not spaces). An easy fix is to change your LINQ a bit.
bool isMadeOfLettersOnly = nameCapInput.All(c => char.IsLetter(c) || char.IsWhiteSpace(c));
So now input with letters or spaces will be considered valid.
In addition, your use of goto is a very bad idea. Generally there should never be any reason to use goto.
To fix this, use a while loop and a method:
public static void Main()
{
bool exit = false;
do {
exit = ProcessInput();
}
while(!exit);
}
private static bool ProcessInput()
{
string nameCapInput = Console.ReadLine();
bool containsInt = nameCapInput.Any(char.IsDigit);
bool isMadeOfLettersOnly = nameCapInput.All(c => char.IsLetter(c) || char.IsWhiteSpace(c));
if (nameCapInput.Equals("exit", StringComparison.CurrentCultureIgnoreCase))
{
return true; //exiting so return true
}
else if (containsInt)
{
Console.WriteLine("You can't capitalize numbers. Use letters only. Try again.");
}
else if (isMadeOfLettersOnly)
{
string upper = nameCapInput.ToUpper();
Console.WriteLine("The uppercase version of your entered text is: {0}", upper);
}
return false; //no exit, so return false
}
This is just a quick refactor, you could make it better.
Fiddle here
Check the documentation: https://learn.microsoft.com/en-us/dotnet/api/system.char.isletter?view=netframework-4.8
Based on the documentation of the IsLetter function, the space is not included in the return true cases.
I would suggest that you use regular expressions for this or change your last case to
else if (!containsInt)
{
var upper = nameCapInput.ToUpper();
Console.WriteLine($"The uppercase version of your entered text is: {upper}");
goto inputCap;
}
Also check the documentation of goto: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/goto
The goto statement transfers the program control directly to a labeled statement.
A common use of goto is to transfer control to a specific switch-case label or the default label in a switch statement.
The goto statement is also useful to get out of deeply nested loops.
You are not in any such case, so you shouldn't use it.

How to make the console wait but then continue without pressing a Key?

I'm fairly new to this community however I'm studying at college on an IT course. And we have been set an assignment to come up with our very own console code. I thought it would be cool and somewhat unique if I program a funny hacker like typerwiter. I have managed to get it to type by itself and be automated so the user doesn't have to do anything for the program to work.
This project is completely experimental and more of a challenge to expand my knowledge and skill however I would like to find out and know how to:
1; Make the program wait.
So for example where my text reads "Initiating decryption..." I would like it to wait, let's say 3 seconds and then carry on. To make it seem as if it's actually processing some sort of data.
2; Make it work on commands.
So I have basic knowledge on switches and if commands. However, I'd like to learn more in-depth on how it all works.
So say in my last text "Would you like to proceed?" I wanted a choice to either close down the console or to carry on with the imaginary decryption. How could I achieve this by then being able to carry on making more text and options for the user to participate?
{
Console.ForegroundColor = ConsoleColor.Green;
var myString = "Initiating decryption..." + Environment.NewLine + "> 248,604 possible combinations found" + Environment.NewLine + "<-> Would you like to proceed?";
foreach (var character in myString)
{
Console.Write(character);
Thread.Sleep(60);
}
Console.WriteLine();
Console.ReadLine();
}
}
you can use a Simple if statement and and while bucle to execute the same all time.
while(true) {
System.Threading.Thread.Sleep(3000); // to waiting 3 seconds
Console.WriteLine("Would you like to proceed ? (Y/N)");
var option = Console.ReadKey();
if (option.ToString().ToUpper() == "N"){
Environment.Exit(0);
}
}
If I understand well you want to ask a question to the user, then do something depending on his input.
A basic orientation would be :
Console.WriteLine("Would you like to proceed ? (Y/N)");
string choice = Console.ReadLine();
if (choice == "y")
{`enter code here`
do something
}
else
{
do something else
}

Simple C# login with 3 attempts [duplicate]

This question already has answers here:
How to add c# login attempts loop in console application?
(3 answers)
Closed 6 years ago.
I need to create a simple C# Sharp program that takes userid and password as input (type string). After 3 wrong attempts user should be rejected.
I have started but I'm not sure how the logic should be properly done.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UserId
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Type username");
String UserId1 = Console.ReadLine();
Console.WriteLine("Type password");
String Pass = Console.ReadLine();
String UserIdCorrect = "test1";
String PassCorrect = "password1";
int MaxAttempts = 3;
Console.ReadKey();
if (UserId1 != UserIdCorrect && Pass != PassCorrect ) {
MaxAttempts++;
}
Console.ReadKey();
}
}
}
First of all, even before writing a single line of code, try to think about naming conventions for a minute or two. This is like "putting foam on your face before having a shave. You can get a shave even without the shaving foam but the experience wouldn't be nice". Try this link for more info [https://msdn.microsoft.com/en-us/library/ms229045(v=vs.110).aspx].
Now moving towards your question, if I have to only fulfill your requirement, this code will be suffice. Here I'm taking "valid" as an identifier for the correct credentials:
<code>
//Login Attempts counter
int loginAttempts = 0;
//Simple iteration upto three times
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Enter username");
string username = Console.ReadLine();
Console.WriteLine("Enter password");
string password = Console.ReadLine();
if (username != "valid" || password != "valid")
loginAttempts++;
else
break;
}
//Display the result
if (loginAttempts > 2)
Console.WriteLine("Login failure");
else
Console.WriteLine("Login successful");
Console.ReadKey();
</code>
Just run the for loop 3 times and if still user enter the wrong entry than just disable the window .
I guess you are a beginner. I've commented the code.
int maxAttempts = 3;
// looping n (maxAttempts) times
for(int i = 0; i < maxAttempts; i++)
{
// get input and check it
}
// do what ever you want here.
// at least show up a message
Many ways. As HebeleHododo commented you could also use a while-loop and check with if-else if your maxAttempts is reached.

i want hide some character from email like Sha***aj#gmail.com [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 8 years ago.
Improve this question
I have developed a application, it is user based application. int this app if user forget his password, then user can reset his password only through his email id and in case if user is not remember his email id which is associated with his account at that time i want retrieve password in a social security numbers like sha***aj#gmail.com. How can i achieve this please help me with this problem that will be appreciated. Thank you.
i have got this code from stak over flow but it is not meet my requirement. It is good for only phone number not for email
public static string GetMaskedEmail(string number)
{
if (String.IsNullOrEmpty(number))
return string.Empty;
if (number.Length <= 12)
return number;
string last12 = number.Substring(number.Length - 12, 12);
var maskedChars = new StringBuilder();
for (int i = 0; i < number.Length - 12; i++)
{
maskedChars.Append(number[i] == '-' ? "-" : "#");
}
return maskedChars + last12;
}
Work is a little slow tonight, so I fired up Xamarin Studio and whipped this up for you. This shouldn't be taken as an example in best coding practices, really not at all.
Though what this will provide is a functioning example, from which you can take and build into your own method and hopefully learn in the process. A great resource for reference, if you get lost at all while reading over any code, is MSDN which if you haven't visited yet I would suggest doing so and bookmarking for future use.
using System;
namespace EmailHash
{
class MainClass
{
public static void Main (string[] args)
{
if (args.Length <= 0)
{
Console.WriteLine ("No values were passed to application.");
return;
}
string email = args[0];
int indexOfAt = email.IndexOf ("#");
if (indexOfAt == -1)
{
Console.WriteLine("Unable to find '#' symbol within email.");
return;
}
int indexStart = 3;
int indexEnd = indexOfAt - 2;
if (indexStart >= indexEnd)
{
Console.WriteLine("Not enough characters in email to mask value.");
return;
}
string hashedEmail = email.Replace(email.Substring(indexStart, indexEnd - indexStart), "***");
Console.WriteLine("Original email: " + email);
Console.WriteLine("Hashed email: " + hashedEmail);
return;
}
}
}

Categories

Resources