I'm trying to create a text-based password log-in for a class project. Unfortunately, it's C#, not python. So I make it so if the user gets it wrong it says incorrect but if they get it correct it says correct.The problem I am having is that I can't loop/retry it when I get it incorrect. Does anyone have suggestions or answers to this? (I have the example code below)
Thanks!
using System;
public class Program
{
public static void Main()
{
int Password = 1234;
Console.WriteLine("Enter the password in order to enter");
Password = Convert.ToInt32(Console.ReadLine());
if (Password == 1234)
{
Console.WriteLine("Processing...");
Console.WriteLine("Access Granted");
}
else
{
Console.WriteLine("Processing...");
Console.WriteLine("Access Denied");
Console.WriteLine("Try again...");
}
}
}
You can do a While loop and break when the password matches. Something like this:
int correctPassword = 1234;
while (true)
{
Console.Write("Enter the password in order to enter: ");
string? informedPassword = Console.ReadLine();
Console.WriteLine("Processing...");
if (informedPassword == correctPassword.ToString())
{
Console.WriteLine("Access granted!");
break;
}
else
{
Console.WriteLine("Access denied!");
Console.WriteLine("Try again...");
}
Console.WriteLine();
}
Related
using System;
namespace SummerWorkTask1
{
class Program
{
static void Main(string[] args)
{
string firstName;
string surname;
string dateOfBirth;
do
{
Console.WriteLine("Please enter your frist name and if at anytime you want to quit enter Q\n");
firstName = Console.ReadLine().ToUpper();
Console.WriteLine("Now enter your surname\n");
surname = Console.ReadLine().ToUpper();
Console.WriteLine("Lastly, enter your date of birth in the format of DD/MM/YY \n");
dateOfBirth = Console.ReadLine().ToUpper();
string customerID = $"{dateOfBirth.Replace("/", "")}{surname.Substring(0, 3)}{firstName.Substring(0, 1)}{firstName.Length} ";
Console.WriteLine(customerID);
} while (!firstName.Equals("Q") || !surname.Equals("Q") || !dateOfBirth.Equals("Q"));
}
}
}
You need to check for Q as you go. Here's the way I would look at it if I were you.
static void Main(string[] args)
{
string Ask(string message)
{
Console.WriteLine(message);
string input = Console.ReadLine().ToUpper();
Console.WriteLine();
return input;
}
while (true)
{
string firstName = Ask("Please enter your first name and if at anytime you want to quit enter Q");
if (firstName.Equals("Q"))
break;
else
{
string surname = Ask("Now enter your surname");
if (surname.Equals("Q"))
break;
else
{
string dateOfBirth = Ask("Lastly, enter your date of birth in the format of DD/MM/YY");
if (dateOfBirth.Equals("Q"))
break;
else
{
string customerID = $"{dateOfBirth.Replace("/", "")}{surname.Substring(0, 3)}{firstName.Substring(0, 1)}{firstName.Length} ";
Console.WriteLine(customerID);
}
}
}
}
}
I'd recommend against using the Environment.Exit(0); option as this only allows you one outcome. There will be few occasions in writing larger programs where you'll actually want to quit like this.
The problem is that the condition you enter in the while() is executing only at the end of the loop and it happend after the CustomerID initiation. Also the fact that you exit the loop is not the right way to close the program.
try this maybe it will help:
static void Main(string[] args)
{
string firstName;
string surname;
string dateOfBirth;
while (true)
{
Console.WriteLine("Please enter your frist name and if at anytime you want to quit enter Q\n");
firstName = Console.ReadLine().ToUpper();
CheckForQ(firstName); //check if user enter q
Console.WriteLine("Now enter your surname\n");
surname = Console.ReadLine().ToUpper();
CheckForQ(surname); //check if user enter q
Console.WriteLine("Lastly, enter your date of birth in the format of DD/MM/YY \n");
dateOfBirth = Console.ReadLine().ToUpper();
CheckForQ(dateOfBirth); //check if user enter q
string customerID = $"{dateOfBirth.Replace("/", "")}{surname.Substring(0, 3)}{firstName.Substring(0, 1)}{firstName.Length} ";
Console.WriteLine(customerID);
}
}
private static void CheckForQ(string line)
{
if (line.Equals("Q"))
{
Environment.Exit(0);
}
}
If I write the following code (inside the Main method):
Console.Write("First name: ");
student.FirstName = Console.ReadLine();
where FirsName is a property of Student class, how can I prevent the user from entering integer characters? Can this be done using try-catch block?
If you want to prevent user from "entering" Numeric Characters, you could do the following.
var value = new StringBuilder();
var run = true;
while (run)
{
var inputKey = Console.ReadKey(true);
switch (inputKey.Key)
{
case ConsoleKey.Enter:
run = false;
Console.WriteLine();
break;
case ConsoleKey.Backspace:
value.Append(inputKey.KeyChar);
break;
default:
if (!char.IsDigit(inputKey.KeyChar))
value.Append(inputKey.KeyChar);
Console.Write(inputKey.KeyChar);
break;
}
}
var name = value.ToString();
You were not very specific, but based on the data you gave you can do something like this using try catch:
class Program
{
static void Main(string[] args)
{
Student student = new Student();
try
{
Console.Write("First name: ");
student.FirstName = Console.ReadLine();
ValidateMyString(student.FirstName);
Console.ReadLine();
}
catch(Exception e)
{
throw e;
}
}
static void ValidateMyString(string s)
{
if (s.Any(char.IsDigit))
{
throw new FormatException();
}
}
}
Here a example in dotnetfiddle.
I'm writing a flesch index calculator and I want to be able to start my program with a console command and the .exe itself. I want to read in .txt files in the console with the command fleschIndexCalc.exe -f "path of the file" and then be able to select the calculation formula either for an english text with the parameter -e or a german text with -g.
When I start it with the console command: I type in the parameters by myself.
When I start it with the .exe: The program asks for the language and I just have to write g ore and press enter.
Now my question: how can I tell my program while starting it with the console that I already chose the language so it doesn't ask me for it again like I started it with the .exe?
Here's what I got:
(If you need more code from my FleschScore.cs ask for it :) )
namespace Flesch_Reading_Ease
{
public class Program
{
public static void Main(string[] args)
{
string fileName = string.Empty;
string[] parameters = new string[] { "-f", "-g", "-e" };
Console.WriteLine("Flesch Reading Ease");
Console.WriteLine("");
if (args.Length == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("error!");
Console.ResetColor();
Console.WriteLine("no file found!");
Console.WriteLine("");
Console.Write("press any key...");
Console.ReadKey();
return;
}
foreach (string arg in args)
{
//------- WHAT TO WRITE HERE? -------
}
fileName = args[0];
FleschScore fs = new FleschScore(fileName);
fs.Run();
}
}
}
My method to choose the language looks like this:
private void SelectLanguage()
{
do
{
Console.WriteLine("choose language:");
Console.WriteLine("- german(g)");
Console.WriteLine("- english(e)");
string lang = Console.ReadLine();
switch (lang.ToUpper())
{
case "D":
_selectedLanguage = Language.German;
break;
case "E":
_selectedLanguage = Language.English;
break;
default:
_selectedLanguage = Language.Undefined;
Console.WriteLine("wrong input. Enter viable letter.");
Console.WriteLine("");
break;
}
} while (_selectedLanguage == Language.Undefined);
}
You basically loop through all the arguments and keep track of what's already entered. Then after that you check if you have all the info you need and pass everything as parameters to whatever method/class needs it.
bool isGerman = false;
bool isEnglish = false;
bool nextEntryIsFileName = false;
string filename = null;
foreach (string arg in args)
{
switch (arg)
{
case "-e":
isEnglish = true;
nextEntryIsFileName = false;
break;
case "-g":
isGerman = true;
nextEntryIsFileName = false;
break;
case "-f":
nextEntryIsFileName = true;
break;
default:
if (nextEntryIsFileName)
{
filename = arg;
nextEntryIsFileName = false;
}
break;
}
}
if (!(isEnglish ^ isGerman))
{
// Select language
}
if (String.IsNullOrEmpty(filename))
{
// Ask for filename
}
var language = ...
FleschScore fs = new FleschScore(language, fileName);
fs.Run();
I am trying to create a simple program in C# that is capable of reading a .TXT file. So far I am able to display an error message if the incorrect file location is typed, however when I input a correct file path the program displays nothing... Any advice/guidance would be much appreciated. Thanks.
`using System;
using System.IO;
class ReadFromFile
{
static void Main()
{
Console.WriteLine ("Welcome to Decrypter (Press any key to begin)");
Console.ReadKey ();
//User selects file they wish to decrypt
int counter = 0;
string line;
string path;
Console.WriteLine ("\nPlease type the path to your file");
path = Console.ReadLine ();
try
{
if (!File.Exists(path))
{
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(path);
while((line = file.ReadLine()) != null)
{
Console.WriteLine (line);
counter++;
}
file.Close();
// Suspend the screen.
Console.ReadLine();
}
}
catch (Exception)
{
Console.WriteLine("The value you entered is incorrect.");
}
}
}`
Try this
using System;
using System.IO;
namespace ConsoleApplication1
{
class ReadFromFile
{
static void Main()
{
Console.WriteLine("Welcome to Decrypter (Press any key to begin)");
Console.ReadKey();
//User selects file they wish to decrypt
int counter = 0;
string line;
string path = "";
try
{
while (true)
{
if (!File.Exists(path))
{
Console.WriteLine("\nPlease type the path to your file");
path = Console.ReadLine();
}
else
{
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(path);
while ((line = file.ReadLine()) != null)
{
Console.WriteLine(line);
counter++;
}
file.Close();
break;
}
}
}
catch (Exception)
{
Console.WriteLine("The value you entered is incorrect.");
}
}
}
}
In the web browser app for windows phone7, If the user types simply "bing.com" in the UrlTExtBox, the UrlTextBox auto-fills "http://www." The following codes shows that. At the same time if the user types simply words(like technology or project glass) without ".com", the UrlTextBox again auto-fills with "http://". But i need, if there is only words then it should search in Google or Bing. Can anybode help me with this? Thanks in advance for your hard work!
private void UrlTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
Uri url;
if (Uri.TryCreate(UrlTextBox.Text, UriKind.Absolute, out url))
{
this.urls[this.currentIndex] = UrlTextBox.Text;
this.browsers[this.currentIndex].Navigate(url);
navigationcancelled = false;
this.browsers[this.currentIndex].Focus();
}
else
{
Navigate(UrlTextBox.Text);
}
}
}
private void Navigate(String address)
{
if (String.IsNullOrEmpty(address)) return;
if (address.Equals("about:blank")) return;
if (!address.StartsWith("http://") &&
!address.StartsWith("https://"))
{
address = "http://" + address;
}
try
{
browsers[this.currentIndex].Navigate(new Uri(address));
}
catch (System.UriFormatException)
{
return;
}
}
In your navivate function check if it is one word in the box, if so check if it ends with .com or .net etc.. if so, add http and send it along, if not append it to the google search url.
Here's a simple console app which demonstrates the logic you should be looking for:
namespace SO10747736
{
using System;
internal enum TestResult
{
TryCreatePass,
ValidWithPrefix,
Search,
DoNothing,
Unknown
}
public class Program
{
public static void Main(string[] args)
{
Test("http://example.com", TestResult.TryCreatePass);
Test("https://example.com", TestResult.TryCreatePass);
Test("https://example", TestResult.TryCreatePass);
Test("example.com", TestResult.ValidWithPrefix);
Test("example", TestResult.Search);
Test("another example", TestResult.Search);
Test(null, TestResult.DoNothing);
Test(string.Empty, TestResult.DoNothing);
Test(" ", TestResult.DoNothing);
Test("about:blank", TestResult.DoNothing);
Console.ReadKey(true);
}
private static void Test(string toTest, TestResult expectedResult)
{
var result = SimulateEnterkeyPressed(toTest);
if (result == expectedResult)
{
Console.WriteLine("{0} was parsed correctly", toTest);
}
else
{
Console.WriteLine("*** {0} was NOT parsed correctly and returned {1} ***", toTest, result);
}
}
private static TestResult SimulateEnterkeyPressed(string toTest)
{
if (string.IsNullOrWhiteSpace(toTest))
{
return TestResult.DoNothing;
}
// Uri.TryCreate will treat this as valid
if (toTest.Equals("about:blank"))
{
return TestResult.DoNothing;
}
Uri url;
if (Uri.TryCreate(toTest, UriKind.Absolute, out url))
{
return TestResult.TryCreatePass;
}
else
{
return TryParse(toTest);
}
}
private static TestResult TryParse(string toTest)
{
if (!toTest.Contains("."))
{
return TestResult.Search;
}
if (!toTest.StartsWith("http://") ||
!toTest.StartsWith("https://"))
{
return TestResult.ValidWithPrefix;
}
return TestResult.Unknown;
}
}
}
Finally got an idea for Matt Lacey's answer. Just add one more if statement to the Navigate.
if (!address.Contains("."))
{
address = " ";
browsers[this.currentIndex].Navigate(new Uri("http://www.google.com/search?q=" + UrlTextBox.Text, UriKind.Absolute));
}
The point is, if i didn't add address = " "; then the UrlTextBox auto-fills http://.
Couldn't you split it by ., and then if array count is one you know it's a single word and should add .com, else you should treat it as a proper link.