I'm new to programming, basically, as you will be able to see everything works up until I want to ask if the details are correct, whatever I type in it will always take the details as correct, I want to be able to type yes or no to the confirmation. I would really appreciate someone explain this to me so i can use bools properly
namespace UserFeedBack.cs
{
class MainClass
{
static void Main(string[] args)
{
Console.Write("Enter your name : ");
string Name = Console.ReadLine();
Console.WriteLine("Hey there, " +Name );
Console.ReadLine();
Console.Write("How old are you : ");
string Age = Console.ReadLine();
Console.WriteLine(" Hello " + Name + " you are " + Age + "!");
Console.Write("bank card account number :");
string AccountNumber = Console.ReadLine();
Console.WriteLine("Thank you! to confirm, is your account number : " + AccountNumber);
Console.ReadLine();
bool y = true;
if (y)
{
Console.WriteLine("Thank you, we can confirm your details are correct");
}
else
{
Console.WriteLine("re enter your details : ");
}
Console.ReadLine();
}
}
}
You've declared your bool property bool y = true;, and doing that sets the value of the bool to be always true. what you need to do is evaluate what the user is typing with Console.ReadLine(). If the user type "Yes" then you change the property to true, else you change it to false, like this:
class MainClass
{
static void Main(string[] args)
{
Console.Write("Enter your name : ");
string Name = Console.ReadLine();
Console.WriteLine("Hey there, " +Name );
Console.ReadLine();
Console.Write("How old are you : ");
string Age = Console.ReadLine();
Console.WriteLine(" Hello " + Name + " you are " + Age + "!");
Console.Write("bank card account number :");
string AccountNumber = Console.ReadLine();
Console.WriteLine("Thank you! to confirm, is your account number : " + AccountNumber);
bool confirmed = Console.ReadLine().ToLower() == "yes";
if (confirmed)
{
Console.WriteLine("Thank you, we can confirm your details are correct");
}
else
{
Console.WriteLine("re enter your details : ");
}
Console.ReadLine();
}
}
Related
I'm attempting to loop through a switch in C# for a simple console application that returns data based on user input. I am new to coding. I know that the Switch works as I tested it before trying to implement my loop. But when I add the code for loop to my program I cannot get it to provide the data.
I tried taking the switch out completely and using independent If statements for each "case" but this was not working either. I'd really like to see the switch work in the loop if it's possible.
static void Main(string[] args)
{
var repeat = true;
while(repeat)
{
Console.WriteLine("Hello. Which instrument would you like to review? Type Quit to exit the program.");
string instruments = Console.ReadLine();
var action = Console.ReadLine();
if (action == instruments)
{
switch (instruments)
{
case "Jazzmaster":
string jazzmasterMake = "Fender";
string jazzmasterModel = "Jazzmaster";
string jazzmasterType = "guitar";
string jazzmasterCountry = "Japan";
int jazzmasterYear = 1997;
string jazzmasterSerial = "A019459";
string jazzmasterColor = "Sunburst";
{
Console.WriteLine("Your " + jazzmasterMake + " " + jazzmasterModel + " is a " + jazzmasterType + " made in " + jazzmasterCountry
+ " in " + jazzmasterYear + " in a " + jazzmasterColor + " color and with a serial number of " + jazzmasterSerial + ".");
}
break;
case "Jaguar":
string jaguarMake = "Fender";
string jaguarModel = "Jaguar";
string jaguarType = "guitar";
string jaguarCountry = "Japan";
int jaguarYear = 1997;
string jaguarSerial = "A035931";
string jaguarColor = "White";
{
Console.WriteLine("Your " + jaguarMake + " " + jaguarModel + " is a " + jaguarType + " made in " + jaguarCountry
+ " in " + jaguarYear + " in a " + jaguarColor + " color and with a serial number of " + jaguarSerial + ".");
}
break;
case "Stratocaster":
string stratocasterMake = "Fender";
string stratocasterModel = "Stratocaster";
string stratocasterType = "guitar";
string stratocasterCounty = "USA";
int stratocasterYear = 2018;
string stratocasterSerial = "US18004688";
string stratocasterColor = "Black";
{
Console.WriteLine("Your " + stratocasterMake + " " + stratocasterModel + " is a " + stratocasterType + " made in " + stratocasterCounty
+ " in " + stratocasterYear + " in a " + stratocasterColor + " color and with a serial number of " + stratocasterSerial + ".");
}
break;
default:
Console.WriteLine("That instrument is not in your collection.");
break;
}
}
else if (action == "Quit")
{
repeat = false;
}
}
}
}
}
Here's an alternative way of implementing your code. I post it not as a direct answer to your question, but as a way of showing an alternative to help your learning.
static void Main(string[] args)
{
Dictionary<string, Instrument> instruments = new Dictionary<string, Instrument>()
{
{ "Jazzmaster", new Instrument() { Make = "Fender", Model = "Jazzmaster", Type = "guitar", Country = "Japan", Year = 1997, Serial = "A019459", Color = "Sunburst", } },
{ "Jaguar", new Instrument() { Make = "Fender", Model = "Jaguar", Type = "guitar", Country = "Japan", Year = 1997, Serial = "A035931", Color = "White", } },
{ "Stratocaster", new Instrument() { Make = "Fender", Model = "Stratocaster", Type = "guitar", Country = "USA", Year = 2018, Serial = "US18004688", Color = "Black", } },
};
while (true)
{
Console.WriteLine("Hello. Which instrument would you like to review? Type Quit to exit the program.");
string input = Console.ReadLine();
if (input.ToLowerInvariant() == "quit")
{
break;
}
else if(instruments.ContainsKey(input))
{
Instrument instrument = instruments[input];
Console.WriteLine($"Your {instrument.Make} {instrument.Model} is a {instrument.Type} made in {instrument.Country} in {instrument.Year} in a {instrument.Color} color and with a serial number of {instrument.Serial}.");
}
else
{
Console.WriteLine("That instrument is not in your collection.");
}
}
}
public class Instrument
{
public string Make { get; init; }
public string Model { get; init; }
public string Type { get; init; }
public string Country { get; init; }
public int Year { get; init; }
public string Serial { get; init; }
public string Color { get; init; }
}
I would just remove action and instruments and the if else and just call the input you get choice, because it's what the user wants. I'm not going to recreate your whole code here, but:
static void Main(string[] args)
{
var repeat = true;
while(repeat)
{
Console.WriteLine("Hello. Which instrument would you like to review? Type Quit to exit the program.");
string choice = Console.ReadLine();
switch (choice)
{
case "Jazzmaster":
// Jazzmaster stuff
break;
case "Jaguar":
// Jaguar stuff
break;
case "Stratocaster":
// Stratocaster stuff
break;
case "Quit"
repeat = false;
break;
default:
Console.WriteLine("That instrument is not in your collection.");
break;
}
}
}
This seems much easier to understand what's going on. There are other tricks you can play to clean up your code, like creating an abstract Instrument class that overrides ToString(), to print whatever attributes you want, but that's beyond the scope of the question you've asked.
Ultimately the problem is that you're trying to get TWO inputs from your existing code.
For the code you shared, you have to to type in instrument twice to get a review. Problem is caused here:
Console.WriteLine("Hello. Which instrument would you like to review? Type Quit to exit the program.");
string instruments = Console.ReadLine();
var action = Console.ReadLine();
if (action == instruments)
Notice Console.ReadLine() is executed twice. In order to enter the if, you have to have have the two input strings that match.
I have an existing .txt file that I would like to use to store my data, but when using this code I get an error at line 39 at switch case 1.
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
public static List<Pw> Site = new List<Pw>();
static void Main(string[] args)
{
string file = #"C: \Users\james\Documents\DataFolder\Vault.txt";
string command = "";
while (command != "exit")
{
Console.Clear();
Console.WriteLine("Please enter a command: ");
command = Console.ReadLine().ToLower();
switch (command)
{
case "1":
AddPw();
File.AppendAllLines(file, Pw.Site);
break;
case "2":
if (File.Exists(file))
{
// Read all the content in one string
// and display the string
string str = File.ReadAllText(file);
Console.WriteLine(str);
}
break;
}
}
}
private static void AddPw()
{
Pw pw = new Pw();
Console.Write("Enter the Username/Email: ");
pw.Username = Console.ReadLine();
Console.Write("Enter Full Name: ");
pw.FullName = Console.ReadLine();
Console.Write("Enter Phone Number: ");
pw.PhoneNumber = Console.ReadLine();
Console.Write("Enter Your Password: ");
string password = Console.ReadLine();
pw.Password = password;
Site.Add(pw);
}
private static void PrintPw(Pw pw)
{
Console.WriteLine("Username/Email: " + pw.Username);
Console.WriteLine("Full Name: " + pw.FullName);
Console.WriteLine("Phone Number: " + pw.PhoneNumber);
Console.WriteLine("Password: " + pw.Password[0]);
Console.WriteLine("-------------------------------------------");
}
private static void ListPw()
{
if (Site.Count == 0)
{
Console.WriteLine("Your address book is empty. Press any key to continue.");
Console.ReadKey();
return;
}
Console.WriteLine("Here are the current people in your address book:\n");
foreach (var pw in Site)
{
PrintPw(pw);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
public class Pw
{
public string Username { get; set; }
public string FullName { get; set; }
public string PhoneNumber { get; set; }
public string Password { get; set; }
}
I have updated your existing function.
using this function you can add and append data in existing file.
private static void AddPw(string filePath)
{
try
{
Pw pw = new Pw();
if (!File.Exists(filePath))
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath))
{
Console.Write("Enter the Username/Email: ");
pw.Username = Console.ReadLine();
sw.WriteLine(pw.Username);
Console.Write("Enter Full Name: ");
pw.FullName = Console.ReadLine();
sw.WriteLine(pw.FullName);
Console.Write("Enter Phone Number: ");
pw.PhoneNumber = Console.ReadLine();
sw.WriteLine(pw.PhoneNumber);
Console.Write("Enter Your Password: ");
pw.Password = Console.ReadLine();
sw.WriteLine(pw.Password);
}
}
else
{
using (StreamWriter sw = File.AppendText(filePath))
{
Console.Write("Enter the Username/Email: ");
pw.Username = Console.ReadLine();
sw.WriteLine(pw.Username);
Console.Write("Enter Full Name: ");
pw.FullName = Console.ReadLine();
sw.WriteLine(pw.FullName);
Console.Write("Enter Phone Number: ");
pw.PhoneNumber = Console.ReadLine();
sw.WriteLine(pw.PhoneNumber);
Console.Write("Enter Your Password: ");
pw.Password = Console.ReadLine();
sw.WriteLine(pw.Password);
}
}
}
catch (Exception ex)
{
}
}
File.AppendAllLines(file, Pw.Site);
In this line, you need to pass an IEnumerable for AppendAllLines to work. You can easily convert Site (which is List<Pw>) to an IEnumerable<string> using the ConvertAll method. Here's one way of achieving this:
Replace that line with this:
File.AppendAllLines(file, Site.ConvertAll<string>(
(p) => string.Format("{0} | {1} | {2} | {3}\n",
p.Username,
p.FullName,
p.PhoneNumber,
p.Password
))
);
This "lambda" basically takes your Pw object and converts it into a string inline.
For example
Console.WriteLine("Please input your age: ");
string age = Console.ReadLine();
Console.WriteLine("Please input your first name: ");
string firstname = Console.ReadLine();
Console.WriteLine("Please input your last name: ");
string lastname = Console.ReadLine();
Console.WriteLine("Thank you!");
Now pretend I have something like this but with a lot of more questions. Then I wouldn't want to keep putting an if statement on each one. How would I make it run this code:
Console.WriteLine("beta")
whenever the user says "alpha" without putting if statements on each user input?
As already suggested, make a function that receives a prompt and returns the response. Inside that, you can check for "alpha" and output "beta", though I suspect that's not ~really~ what you need to do:
static void Main(string[] args)
{
string age = GetResponse("Please input your age: ");
string firstname = GetResponse("Please input your first name: ");
string lastname = GetResponse("Please input your last name: ");
Console.WriteLine("Thank you!");
Console.Write("Press Enter to Quit");
Console.ReadLine();
}
static string GetResponse(string prompt)
{
Console.Write(prompt);
string response = Console.ReadLine();
if (response == "alpha")
{
Console.WriteLine("beta");
}
return response;
}
For clarification I'm using Microsoft visual studio and trying to turn the cmd format into a cute little interactive terminal. I'm a bare basics beginner and I'm aware this may be an ambitious project for someone of my skill. The only thing I'm confused about at the moment is how to tell the program that I want it to start itself over within the constraints of an else if statement.
static void Main(string[] args)
{
Console.WriteLine("What's your name?");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
Console.WriteLine("What's your age?");
string age = Console.ReadLine();
Console.WriteLine("Your name is " + name + " and you are " + age + " years old, Correct?");
string val = Console.ReadLine();
if (val == "yes")
{
Console.WriteLine("Data confirmed, thank you for your cooperation!");
}
else if (val == "no")
{ //I would like to restart the code if this condition is met
Console.WriteLine("Incorrect data provided, please try again");
}
else
{ //The issue with this line is that I want it to just ask if the data is correct again
Console.WriteLine("That is not a valid response, try answering with a yes or no");
}
Try something like this. Basically, you're wrapping your code in a loop (in this case, a "do...while" loop, and adding a flag indicating whether or not the program should "start over."
static void Main(string[] args)
{
bool finished;
do
{
finished = true;
Console.WriteLine("What's your name?");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
Console.WriteLine("What's your age?");
string age = Console.ReadLine();
Console.WriteLine("Your name is " + name + " and you are " + age + " years old, Correct?");
string val = Console.ReadLine();
while(val != "yes" && val != "no") {
Console.WriteLine("That is not a valid response, try answering with a yes or no");
val = Console.ReadLine();
}
if (val == "yes") {
Console.WriteLine("Data confirmed, thank you for your cooperation!");
}
else if (val == "no") {
Console.WriteLine("Incorrect data provided, please try again");
finished = false;
}
} while(!finished);
}
You can break your code out into a separate method, and call it from your Main() method. Then, in your else statement, you can have your new method call itself so that it executes again. (Disclaimer: It's been a long time since I've written C#.)
static void Main(string[] args) {
askName();
}
static void askName() {
Console.WriteLine("What's your name?");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
Console.WriteLine("What's your age?");
string age = Console.ReadLine();
Console.WriteLine("Your name is " + name + " and you are " + age + " years old, Correct?");
string val = Console.ReadLine();
if (val == "yes") {
Console.WriteLine("Data confirmed, thank you for your cooperation!");
} else if (val == "no") {
askName();
} else {
//The issue with this line is that I want it to just ask if the data is correct again
Console.WriteLine("That is not a valid response, try answering with a yes or no");
}
}
Hi I would like to prevent users from entering nothing in the input field.
I've tried using an if else but the console keeps crashing when there's no input. (for both user input and ldap address input ==> I want it to show "No input detected." and allow the user to re-enter the username)
And if I used (results == " "), I would get a error:
"Operator '==' cannot be applied to operands of type
'System.DirectoryServices.SearchResult' and 'string'"
Is there any way for me to resolve this? The codes are as shown below.
Affected codes from line 16 onwards (for the top block of codes)
if (results != null)
{
//Check is account activated
bool isAccountActived = IsActive(results.GetDirectoryEntry());
if (isAccountActived)
Console.WriteLine(targetUserName + "'s account is active.");
else
Console.WriteLine(targetUserName + "'s account is inactive.");
//Check is account expired or locked
bool isAccountLocked = IsAccountLockOrExpired(results.GetDirectoryEntry());
if (isAccountLocked)
Console.WriteLine(targetUserName + "'s account is locked or has expired.");
else
Console.WriteLine(targetUserName + "'s account is not locked or expired.");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n\n");
}
else if (results == " ")
{
//no user entered
Console.WriteLine("No input detected!");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n");
}
else
{
//user does not exist
Console.WriteLine("User not found!");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n");
}
If it helps, I've attached the whole code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Data.SqlClient;
namespace ConsoleApplication2
{
class Program
{
const String serviceAccountUserName = "mobileuser1";
const String serviceAccountPassword = "password123$";
const int UF_LOCKOUT = 0x0010;
const int UF_PASSWORD_EXPIRED = 0x800000;
static void Main(string[] args)
{
string line;
Console.WriteLine("Welcome to account validator V1.0.\n"+"Please enter the ldap address to proceed.");
Console.Write("\nEnter address: ");
String ldapAddress = Console.ReadLine();
try
{
if (ldapAddress != null)
{
Console.WriteLine("\nQuerying for users in " + ldapAddress);
//start of do-while
do
{
Console.WriteLine("\nPlease enter the user's account name to proceed.");
Console.Write("\nUsername: ");
String targetUserName = Console.ReadLine();
bool isValid = false;
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ldapAddress))
{
// validate the credentials
isValid = pc.ValidateCredentials(serviceAccountUserName, serviceAccountPassword);
// search AD data
DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapAddress, serviceAccountUserName, serviceAccountPassword);
//create instance fo the directory searcher
DirectorySearcher desearch = new DirectorySearcher(entry);
//set the search filter
desearch.Filter = "(&(sAMAccountName=" + targetUserName + ")(objectcategory=user))";
//find the first instance
SearchResult results = desearch.FindOne();
if (results != null)
{
//Check is account activated
bool isAccountActived = IsActive(results.GetDirectoryEntry());
if (isAccountActived) Console.WriteLine(targetUserName + "'s account is active.");
else Console.WriteLine(targetUserName + "'s account is inactive.");
//Check is account expired or locked
bool isAccountLocked = IsAccountLockOrExpired(results.GetDirectoryEntry());
if (isAccountLocked) Console.WriteLine(targetUserName + "'s account is locked or has expired.");
else Console.WriteLine(targetUserName + "'s account is not locked or expired.");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n\n");
}
else if (results == " ")
{
//no user entered
Console.WriteLine("No input detected!");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n");
}
else
{
//user does not exist
Console.WriteLine("User not found!");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n");
}
}//end of using
}//end of do
//leave console when 'bye' is entered
while ((line = Console.ReadLine()) != "bye");
}//end of if for ldap statement
else if (ldapAddress == " ")
{
Console.WriteLine("No input detected.");
Console.ReadLine();
Console.WriteLine("\nEnter bye to exit.");
Console.ReadLine();
Console.WriteLine("Press any key to continue.\n");
Console.ReadLine();
}
else
{
Console.WriteLine("Address not found!");
Console.ReadLine();
Console.WriteLine("\nEnter bye to exit.");
Console.ReadLine();
Console.WriteLine("Press any key to continue.\n");
Console.ReadLine();
}
}//end of try
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
} //end of main void
static private bool IsActive(DirectoryEntry de)
{
if (de.NativeGuid == null) return false;
int flags = (int)de.Properties["userAccountControl"].Value;
return !Convert.ToBoolean(flags & 0x0002);
}
static private bool IsAccountLockOrExpired(DirectoryEntry de)
{
string attribName = "msDS-User-Account-Control-Computed";
de.RefreshCache(new string[] { attribName });
int userFlags = (int)de.Properties[attribName].Value;
return userFlags == UF_LOCKOUT || userFlags == UF_PASSWORD_EXPIRED;
}
}
}
You should put the ReadLine in a loop.
string UserName = "";
do {
Console.Write("Username: ");
UserName = Console.ReadLine();
if (!string.IsNullOrEmpty(UserName)) {
Console.WriteLine("OK");
} else {
Console.WriteLine("Empty input, please try again");
}
} while (string.IsNullOrEmpty(UserName));
You basically repeat the prompt over and over until the string entered by the user is no longer null or empty.
Best method would probably be to create a new function to get a non empty input:
private static string GetInput(string Prompt)
{
string Result = "";
do {
Console.Write(Prompt + ": ");
Result = Console.ReadLine();
if (string.IsNullOrEmpty(Result)) {
Console.WriteLine("Empty input, please try again");
}
} while (string.IsNullOrEmpty(Result));
return Result;
}
You can then just use the function to get your inputs like:
static void Main(string[] args)
{
GetInput("Username");
GetInput("Password");
}
Result:
Try using the code :
(!string.IsNullOrEmpty(input));
This is user first name and last name string
//Make container for the user first name and last name
string myFirstName = "";
string myLastName = "";
//Do while loop
do
{
//Welcomes user to the app and asks for first name then asks for last name
Console.WriteLine("Welcome");
Console.WriteLine("Enter first name: ");
//Takes users first name and last name and saves it in myFirstName and myLastName
myFirstName = Console.ReadLine();
Console.Write("Enter Last name: ");
myLastName = Console.ReadLine();
Console.WriteLine();
//If the first AND (&&) last name is not empty because the user entered first name and last name then display the hello message
if (!string.IsNullOrEmpty(myFirstName) && !string.IsNullOrEmpty(myLastName))
{
Console.WriteLine("Hello " + myFirstName + " " + myLastName + " hope you enjoy your day");
}
else //Else the first name or last name is left empty then display the error message
{
Console.WriteLine("Please enter your first name and last name");
Console.WriteLine();
}
//While if either the first name OR (||) last name is empty then keep asking the user for input
} while (string.IsNullOrEmpty(myFirstName) ||
string.IsNullOrEmpty(myLastName));
Console.ReadLine();
Output: