In and Out in C# Console Application - c#

If I enter "01" it will output "IN" and if I input "01" again it will out but the problem is I need to OUT the first number I enter before I can IN another number. Can someone help me????
class Program
{
static string [] num = {"01","02","03"};
static string en;
static string en1;
static void Main()
{
while (true)
{
Console.Clear();
Console.Write("Enter your code: ");
en = Console.ReadLine();
for (int i = 0; i < num.Length; i++)
if (en == num[i])
{
Console.Write("In");
Console.ReadLine();
Console.Clear();
Console.Write("Enter your code: ");
en1 = Console.ReadLine();
if (en1 == en)
{
Console.Write("Out");
Console.ReadLine();
Main();
}
}
}
}
}

Tried to keep it simple to follow, if you're confused by any part please ask
class Program
{
static List<string> num = new List<string> (){ "01", "02", "03" };
static string en;
static string en1;
static void Main()
{
while (true) {
Console.Write("Enter your code: ");
if (String.IsNullOrEmpty(en)) { //check en isn't set yet
en = Console.ReadLine(); // set en
if (num.Contains(en)){ // if en exists in the num list proceed
Console.WriteLine("IN");
} else {
en = null; //if it doesn't null it and start again
}
} else {
en1 = Console.ReadLine(); //read in the value to compare
if (en == en1) { //compare the original input to this
en = null; //if they're the same, null the original
Console.WriteLine("OUT");
}
}
}
}
}

Related

Printing spaces between characters for answer to hangman game in C#

My apologies for asking yet another question, but I am struggling to get the desired output for my hangman program. When the user finds a correct letter, I would like it to display a space between letters and underscores; I can only get it to output a space after a letter and not between as desired. Also, when the secretword is guessed and the user wins, I would like the secret word to be output with spaces between the letters (eg. M A R I O). I have tried using +" " in various places, but still struggling to get the desired output. Any help would be greatly appreciated.
My code is as follows...
static void Main()
{
Console.Title = ("Hangman Game");
string[] secretWords = {
"mario", /*"sonic", "thelegendofzelda", "donkeykong", "luigi",
"peach", "link", "laracroft", "bowser", "kratos",
"playstation", "nintendo", "tetris", "grandtheftauto",
"finalfantasy", "thelastofus", "ghostoftsushima", "horizonzerodawn",
"halo", "forza", "crashbandicoot", "worldofwarcraft", "callofduty",
"fortnite", "animalcrossing", "doom", "metalgearsolid", "minecraft",
"residentevil", "pacman", "spaceinvaders", "asteroids",
"streetfighter", "mortalkombat", "supermariokart", "pokemon",
"bioshock", "tombraider"*/
};
Random R = new Random();
string secretword = secretWords[R.Next(secretWords.Length)];
List<string> letterGuessed = new List<string>();
int live = 5;
Console.WriteLine("Welcome To Hangman!");
Console.WriteLine("Enter a letter to guess for a {0} Letter Word", secretword.Length);
Console.WriteLine("You Have {0} Lives remaining \n", live);
Isletter(secretword, letterGuessed);
while (live > 0)
{
string input = Console.ReadLine();
if (letterGuessed.Contains(input))
{
Console.WriteLine("You Entered Letter [{0}] Already", input);
Console.WriteLine("Try a Different Letter \n");
continue;
}
letterGuessed.Add(input);
if (IsWord(secretword, letterGuessed))
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(secretword);
Console.WriteLine("Congratulations!");
break;
}
else if (secretword.Contains(input))
{
Console.WriteLine("Good Entry\n");
string letters = Isletter(secretword, letterGuessed);
Console.Write(letters);
Console.WriteLine("\n");
}
else
{
Console.WriteLine("That Letter Is Not In My Word");
live -= 1;
Console.WriteLine("You Have {0} Lives Remaining", live);
}
Console.WriteLine();
if (live == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Game Over! \nMy Secret Word is [ {0} ]", secretword);
break;
}
}
Console.ReadKey();
}
static bool IsWord(string secretword, List<string> letterGuessed)
{
bool word = false;
for (int i = 0; i < secretword.Length; i++)
{
string c = Convert.ToString(secretword[i]);
if (letterGuessed.Contains(c))
{
word = true;
}
else
{
return word = false;
}
}
return word;
}
static string Isletter(string secretword, List<string> letterGuessed)
{
string correctletters = "";
for (int i = 0; i < secretword.Length; i++)
{
string c = Convert.ToString(secretword[i]);
if (letterGuessed.Contains(c))
{
correctletters += c;
}
else
{
correctletters += "_ ";
}
}
return correctletters;
}
}
}
Console.WriteLine(string.Join(" ", secretword.ToUpper().ToCharArray()));
worked as expected. Many thanks #41686d6564

C# how to set a conditional statement to except user input?

I have a simple console App that converts pounds to kilograms and vice-versa. What I'm attempting to do is if the user enters lb then run the function to convert pounds to kilograms, else if the user enters kg, then run the function to convert kilograms to pounds.
During the setup part of the condition in main, I get an error "Use of unassigned local variable 'lb'
...The Code (snippets):
//method to convert KG to Lbs
public void ConvertKg()
{
Console.WriteLine("C# KG to LB program\n");
Console.Write("Enter a number in KG: ");
double kilograms = Convert.ToDouble(Console.ReadLine());
double pounds = kilograms * 2.20462262185;
Console.WriteLine(kilograms + " kilograms is " + pounds + " pounds");
}
//method to convert Lbs to KG
public void ConvertLb()
{
Console.WriteLine("C# LB to KG program\n");
Console.Write("Enter a number in lbs:");
double pounds_userEntry = Convert.ToDouble(Console.ReadLine());
double kilogram_userEntry = pounds_userEntry * 0.453592;
Console.WriteLine(kilogram_userEntry + " kilograms is " + pounds_userEntry + " pounds");
}
...main:
string lb, kg;
string userInput = "";
Console.Write("Enter either lb or kg:");
if(userInput == lb) // where the error occurs
{
var k = new ConvertNumber();
k.ConvertLb();
}
else
{
var l = new ConvertNumber();
l.ConvertKg();
}
Console.ReadLine();
...the problem seems to be within the approach I'm using to set up the conditional statement to accept the user's input. ...could I get some help as to what I'm doing wrong?
There is no need to do string lb, kg;, so you can leave it out.
userInput is assigned to "", but it should probably contain something from the user.
Replace
string userInput = "";
with
Console.Write("Enter either kg or lb: ");
string userInput = Console.ReadLine() // Console.ReadLine enables the user to type some text and returns it
Because
Console.Write("Enter either kg or lb");
has been done now, you can leave it out afterwards.
Now you can compare userInput with "lb" and "kg".
Replace
if(userInput == lb)
{
var k = new ConvertNumber();
k.ConvertLb();
}
else
{
var l = new ConvertNumber();
l.ConvertKg();
}
Console.ReadLine();
with
if (userInput == "lb") {
ConvertLb();
} else if (userInput == "kg") {
ConvertKg();
} else {
Console.WriteLine("Your input was neither lb nor kg");
}
Final code (main):
Console.Write("Enter either kg or lb: ");
string userInput = Console.ReadLine() // Console.ReadLine enables the user to type some text and returns it
if (userInput == "lb") { // The user typed "lb"
ConvertLb();
} else if (userInput == "kg") { // The user typed "kg"
ConvertKg();
} else { // The user typed neither "lb" nor "kg"
Console.WriteLine("Your input was neither lb nor kg");
}
As the comments are mentioning, you have to either initialize the lb variable with "lb" or to compare the userInput directly to the string "lb" as Rakesh is writing in comments.
Also I've seen that you don't read the user input.
Below I've created a quick sample code that should do the job that you expect and should be easy to understand.
class Program
{
public const string Lb = "lb"; //User options as constants
public const string Kg = "kg";
static void Main(string[] args)
{
string userInput = GetUserInput();
try
{
ConvertUserInput(userInput);
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message); // Show error message
userInput = GetUserInput(); // Get user input again
ConvertUserInput(userInput);
}
Console.ReadLine();
}
private static string GetUserInput()
{
Console.Write("Enter either lb or kg:");
string userInput = Console.ReadLine();
return userInput;
}
private static void ConvertUserInput(string userInput)
{
// Guard for throwing an error when the user enters another value
if (!IsValidUserInput(userInput))
throw new ArgumentException("Input value is not lb or kg");
if (ConvertFromPoundsToKg(userInput)) // where the error occurs
{
var k = new ConvertNumber();
k.ConvertLb();
}
else
{
var l = new ConvertNumber();
l.ConvertKg();
}
}
/// <summary>
/// userInput is either "lb" or "kg"
/// </summary>
/// <param name="userInput"></param>
/// <returns></returns>
private static bool IsValidUserInput(string userInput)
{
return ConvertFromPoundsToKg(userInput) || (ConvertFromKgToPounds(userInput));
}
private static bool ConvertFromKgToPounds(string userInput)
{
return userInput == Kg;
}
private static bool ConvertFromPoundsToKg(string userInput)
{
return userInput == Lb;
}
}
The problem is that the variable lb is not initialized. It doesn't have a value that you could compare against. I've changed your code to solve this problem. Next steps would be to get the "number" the user entered before the unit and pass it to a unit coversion function and output it to the user again. This will be left for you to do ;)
class Program
{
static void Main(string[] args)
{
//string lb, kg;
//string userInput = "";
Console.Write("Enter either lb or kg:");
string input = Console.ReadLine();
string unit = input.Substring(input.Length-2);
if (unit == "lb") // where the error occurs
{
int k = ConvertNumber();
Console.WriteLine(k + "kg");
//k.ConvertLb();
}
else if (unit == "kg")
{
int l = ConvertNumber();
Console.WriteLine(l + "lb");
//l.ConvertKg();
}
else
{
Console.WriteLine("invalid unit");
}
Console.ReadLine();
}
static int ConvertNumber()
{
Console.WriteLine("convert");
return 123;
}
}

How To Display That an Array is Full

I am working on a simple code that asks for the name, age, and gender of at most 5 patients. After each patient, it should ask to input another patient or return to main menu. Once 5 have been input into an array, there should be a prompt to the user that the array is full.
My problem is the code asks for name,age and gender 5 times upfront, and does not give any indication the array is full. How would I change the code to reflect that and still save the inputs? (Code below).
class MainClass
{
enum Gender { female, male }
struct Record
{
public string _Name;
public int _Age;
public Gender _Gender;
}
public static void Main(string[] args)
{
//title
Console.Write("\t\t\t\t\tPatient Records\n");
string selection = "";
Record[] patients = new Record[5];
GetRecords(patients);
Console.Write("a. Add\n d.Display\ns. Stats\nq. Quit");
Console.Write("Your selection: ");
selection = Console.ReadLine();
switch (selection)
{
case "a":
GetRecords(patients);
break;
case "d":
break;
case "s":
Stats(patients);
break;
case "q":
//CUtility.Pause();
break;
}
}
static void GetRecords(Record[] patient_rec)
{
for (int i = 0; i < patient_rec.Length; i++)
{
Console.Write("Enter your age: ");
int.TryParse(Console.ReadLine(), out patient_rec[i]._Age);
Console.Write("Enter your name: ");
patient_rec[i]._Name = Console.ReadLine();
Console.Write("Enter your gender (female or male): ");
Gender.TryParse(Console.ReadLine(), out patient_rec[i]._Gender);
}
}
static void Stats(Record[]patient_rec)
{
}
}
I would suggest trying to make your code a little easier to read - and more robust.
Try this:
static void GetRecords(Record[] patient_rec)
{
for (int i = 0; i < patient_rec.Length; i++)
{
Console.WriteLine("Record {0} of {1} entry", i + 1, patient_rec.Length);
patient_rec[i] = new Record()
{
_Age = AskInteger("Enter your age: "),
_Name = AskString("Enter your name: "),
_Gender = AskGender("Enter your gender (female or male): "),
};
string ask = "";
while (string.IsNullOrEmpty(ask) || (ask.ToLower()[0] != 'y' && ask.ToLower()[0] != 'n'))
{
Console.WriteLine("Continue? yes or no (then hit enter)");
ask = Console.ReadLine();
}
if (ask.ToLower()[0] == 'y')
{
continue;
}
break;
}
Console.WriteLine("Thank you. Input completed.");
}
To make this work you need these three input functions:
private static int AskInteger(string message)
{
int result;
Console.WriteLine(message);
string input = Console.ReadLine();
while (!int.TryParse(input, out result))
{
Console.WriteLine("Invalid input.");
Console.WriteLine(message);
input = Console.ReadLine();
}
return result;
}
private static string AskString(string message)
{
Console.WriteLine(message);
string input = Console.ReadLine();
while (string.IsNullOrWhiteSpace(input))
{
Console.WriteLine("Invalid input.");
Console.WriteLine(message);
input = Console.ReadLine();
}
return input;
}
private static Gender AskGender(string message)
{
Gender result;
Console.WriteLine(message);
string input = Console.ReadLine();
while (!Gender.TryParse(input, out result))
{
Console.WriteLine("Invalid input.");
Console.WriteLine(message);
input = Console.ReadLine();
}
return result;
}
Your loop is only set to go to the size of the array, so logically you could show a message after the loop (this will get hit when the loop finishes).
If you were controlling your array access in a while loop then just compare your indexer i to the length of the array (patient_rec.Length), if it equals or exceeds the length then show the message.
I would do it in a simpler way:
enum Gender { female, male }
struct Record
{
public string _Name;
public int _Age;
public Gender _Gender;
}
static void Main(string[] args)
{
//title
Console.Write("\t\t\t\t\tPatient Records\n");
IList<Record> patients = GetRecords(5);
SchedulePatients(patients);
}
static void SchedulePatients(IList<Record> patients)
{
Console.Write("a. Add\n d.Display\ns. Stats\nq. Quit");
Console.Write("Your selection: ");
string selection = Console.ReadLine();
switch (selection)
{
case "a":
patients.Add(GetRecord());
SchedulePatients(patients);
break;
case "d":
break;
case "s":
Stats(patients);
break;
case "q":
//CUtility.Pause();
break;
}
}
static IList<Record> GetRecords(int amount)
{
IList<Record> patients = new List<Record>();
for (int i = 0; i < amount; i++)
{
patients.Add(GetRecord());
}
return patients;
}
static Record GetRecord()
{
Record patient = new Record();
Console.Write("Enter your age: ");
int.TryParse(Console.ReadLine(), out patient._Age);
Console.Write("Enter your name: ");
patient._Name = Console.ReadLine();
Console.Write("Enter your gender (female or male): ");
Enum.TryParse(Console.ReadLine(), out patient._Gender);
return patient;
}
static void Stats(IList<Record> patients)
{
foreach (var patient in patients)
{
Console.WriteLine(string.Concat("Name: ", patient._Name, " Age: ", patient._Age, " Gender: ", patient._Gender));
}
Console.ReadLine();
}
}
If you would like to meet the requirements with the smallest change possible, you just need to add the bit about prompting the user.
static void GetRecords(Record[] patient_rec)
{
for (int i = 0; i < patient_rec.Length; i++)
{
Console.Write("Enter your age: ");
int.TryParse(Console.ReadLine(), out patient_rec[i]._Age);
Console.Write("Enter your name: ");
patient_rec[i]._Name = Console.ReadLine();
Console.Write("Enter your gender (female or male): ");
Gender.TryParse(Console.ReadLine(), out patient_rec[i]._Gender);
Console.Write("Enter another (Y/N)? ");
var s = Console.ReadLine();
if (s.ToUpper() != "Y") return;
}
Console.WriteLine("You've entered the maximum number of records.");
}

How can I add in code to make it impossible for a user to input an answer that is not listed? C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kenneth_ForquerENG_115
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Kenneth Forquer ENG 115");
This is where i store my questions and answers
List<Question> question = new List<Question>
{
new Question("What stage bleed air is used to start the engine?", new string[] { "8th", "9th", "1st", "13th" }, Question.multipleChoice, 2),
new Question("Igniters spark to combust the fuel.", new string[] { "true", "false" }, Question.trueAndFalse, 0),
new Question("What is the 1st stage in the cycle of the Gas turbine?", new string[] { "Intake", "Exhaust", "Power", "Combustion" }, Question.multipleChoice, 0),
new Question("What is the 3rd stage in the cycle of the Gas turbine?", new string[] { "Compression", "Combustion", "Intake", "Exhaust" }, Question.multipleChoice, 1),
new Question(" What is the last stage in the cycle of the Gas turbine?", new string[] { "Compression", "Power", "Intake", "Exhaust" }, Question.multipleChoice, 3),
new Question("Ngg refers to speed.", new string[] { "true", "false" }, Question.trueAndFalse, 0),
new Question("Npt refers to torque", new string[] { "true", "false" }, Question.trueAndFalse, 1),
new Question("What are the LM2500 metering points?", new string[] { "3", "2", "5.4", "All of the above" }, Question.multipleChoice, 3),
new Question("Which of these are a component of the compressor?", new string[] { "Inlet Plenum", "Gearbox", "Stator", "All of the above" }, Question.multipleChoice, 2),
new Question("What company manufactures the LM2500?", new string[] { "GM", "Ford", "Toyota", "Rolls Royce" }, Question.multipleChoice, 3)
};
for (int i = 0; i < question.Count; i++)
{
Console.WriteLine("--------------------------------");
Console.WriteLine("Question #" + (1 + i).ToString());
if (question[i].Ask())
{
Results.AddResult(question[i]);
Console.WriteLine("Press any key to continue to the next question.");
//Console.WriteLine("--------------------------------");
}
else
{
Results.AddResult(question[i]);
}
Console.Clear();
}
Console.WriteLine("--------------------------------");
Console.WriteLine("End of the first attempt.");
int tempScore = 0;
for (int i = 0; i < Results.firstResults.Count; i++)
{
if (Results.firstResults[i].isCorrect)
{
tempScore++;
}
}
Console.WriteLine("Your current mark is: " + tempScore + "/" + Results.firstResults.Count.ToString());
Console.WriteLine("--------------------------------");
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
Results.RunSecondAttemp();
Console.WriteLine("--------------------------------");
Console.WriteLine("End of the Quiz!");
int tempFinalScore = 0;
for (int i = 0; i < Results.finalResults.Count; i++)
{
if (Results.finalResults[i].isCorrect)
{
tempFinalScore++;
}
}
Console.WriteLine("Your final mark is: ");
Console.WriteLine(tempFinalScore + "/" + Results.finalResults.Count.ToString());
if (tempFinalScore > 5)
{
Console.WriteLine("Good Job!");
}
else
{
Console.WriteLine("Better luck next time...");
}
Console.WriteLine("--------------------------------");
Console.WriteLine("Press any key to exit the console...");
Console.ReadKey();
}
}
}
namespace Kenneth_ForquerENG_115
{
class Question
{
public string question;
public string[] answers;
public bool isCorrect;
public string inputAnswer;
private int correctIndex;
private string questionType;
public static string trueAndFalse = "TF";
public static string multipleChoice = "MC";
Here is where the input for the questions are.
public Question(string q, string[] answersList, string typeOfQuestion, int correctAnswer)
{
question = q;
questionType = typeOfQuestion;
if (questionType == multipleChoice)
answers = new string[4];
else if (questionType == trueAndFalse)
answers = new string[2];
for (int i = 0; i < answersList.Length; i++)
{
this.answers[i] = answersList[i];
}
correctIndex = correctAnswer;
}
public bool Ask()
{
Console.WriteLine(question);
if (questionType == multipleChoice)
{
Console.WriteLine("Input an answer from the following possibilities...");
}
else
{
Console.WriteLine("Please input 'true' or 'false'... ");
}
for (int i = 0; i < answers.Length; i++)
{
Console.WriteLine(answers[i]);
}
Console.WriteLine("--------------------------------");
inputAnswer = Console.ReadLine();
if (inputAnswer == answers[correctIndex])
{
Console.Clear();
Console.WriteLine("Correct!");
isCorrect = true;
Console.WriteLine("Press any key to continue to the next question.");
Console.ReadKey();
}
else
{
Console.Clear();
Console.WriteLine("Incorrect.");
isCorrect = false;
Console.WriteLine("Press any key to continue to the next question.");
Console.ReadKey();
}
return isCorrect;
}
public void PrintQuestion()
{
Console.WriteLine(question);
if (questionType == multipleChoice)
{
Console.WriteLine("Input an answer from the following possibilities...");
}
else
{
Console.WriteLine("Please input 'true' or 'false'... ");
}
for (int i = 0; i < answers.Length; i++)
{
Console.WriteLine(answers[i]);
}
}
}
}
namespace Kenneth_ForquerENG_115
{
static class Results
{
public static List<Question> firstResults = new List<Question>();
public static List<Question> finalResults = new List<Question>();
public static void AddResult(Question questionResult)
{
firstResults.Add(questionResult);
}
public static void AddFinalResult(Question question)
{
finalResults.Add(question);
}
public static void RunSecondAttemp()
{
Console.Clear();
Console.WriteLine("Attempt #2:");
for (int i = 0; i < firstResults.Count; i++)
{
Console.WriteLine("\n--------------------------------");
Console.WriteLine("\nQuestion " + (1 + i).ToString());
if (firstResults[i].isCorrect)
{
Console.WriteLine("\nThis one was correct!");
firstResults[i].PrintQuestion();
Console.WriteLine("Your answer: " + firstResults[i].inputAnswer);
AddFinalResult(firstResults[i]);
Console.WriteLine("Press any key to continue to the next question.");
Console.ReadKey();
}
else
{
Console.WriteLine("This one was wrong on the first attempt! Please try again.");
if (firstResults[i].Ask())
{
AddFinalResult(firstResults[i]);
Console.WriteLine("Press any key to continue to the next question.");
}
else
{
AddFinalResult(firstResults[i]);
}
Console.WriteLine("\n--------------------------------");
}
Console.Clear();
}
}
}
}
Basically what I am trying to do is make it where the user can only input the answers to the questions. If they type in something not listed it will display an error message, something like "incorrect input, please choose from given answers." So if they type something not listed that message would appear and then go back to the question until they type on of the choices.
One option would be to check if their answer is among the answer choices before checking if the answer is correct. You could do it like this:
while (Array.IndexOf(answers, inputAnswer) < 0)
{
Console.WriteLine("incorrect input, please choose from given answers.");
inputAnswer = Console.ReadLine();
}
Array.IndexOf will return -1 if inputAnswer is not in the answers array. The while loop will not break until the user inputs an answer that is in the answers array, and inputAnswer will contain an answer that is in answers when the loop breaks.
This would go in the Ask method before the line containing
if (inputAnswer == answers[correctIndex])

How to make number Count in loop in c#?

This is a simple begginer program with setter and getter concept
now i have to make it to first enter user name and password to get welcomed
and IF I ENTER WRONG INFO IT SHOULD DISPLAY INVALID AND 5 TRIES LEFT THEN if i again enter wrong info it should display 4 tries left and so on and finally when all tries are over it should hang the program or lock the screen or so
using System;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
}
else
{
Console.Clear();
Console.WriteLine("Invalid");
Console.WriteLine("\n \n \n To try again enter y");
int n = 5;
string yes = Console.ReadLine();
if (yes == "y")
{
while (n >= 1)
{
Console.Write(n + " Tries left");
goto label1;
n = --n;
}
}
}
Console.ReadKey();
}
}
class demo
{
private string name, pass;
public void setName(string name)
{
this.name = name;
}
public string getName()
{
return name;
}
public void setPass(string pass)
{
this.pass = pass;
}
public string getPass()
{
return pass;
}
}
}
Please suggest a simple begginers code to make the loop work and make the count down
A while loop should suffice. Using a boolean to detect successful password entry.
When entered, it will break out of the loop.
invalid attempts will decrement the AttemptsLeft int.
Note: I haven't tried this in Visual Studio, the logic should be sound, but I recommend debugging and stepping through it to test if it meets your criteria.
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
bool SuccessfulPassword = false;
int AttemptsLeft = 5;
while(!SuccessfulPassword && AttemptsLeft > 0){
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
SuccessfulPassword = true;
}
}
else
{
AttemptsLeft--;
Console.Clear();
Console.WriteLine("Invalid");
Console.WriteLine("\n \n \n To try again enter y");
int n = 5;
string yes = Console.ReadLine();
if (yes == "y")
{
Console.Write(AttemptsLeft + " Tries left");
}
}
Console.ReadKey();
}
}
try this updated main method:
static void Main(string[] args)
{
demo obj = new demo();
int n = 5;
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
//Console.Clear();
label1:
Console.WriteLine("\n");
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit" && obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
else
{
//Console.Clear();
if (n < 1)
{
//Add ur screenlock n hang prog code
Console.Clear();
Console.WriteLine("ScreenLock");
}
else
{
Console.WriteLine("\n Invalid");
Console.WriteLine("\n To try again enter y");
string yes = Console.ReadLine();
Console.WriteLine("\n");
if (yes == "y")
{
while (n >= 1)
{
Console.Write(n + " Tries left");
n = --n;
goto label1;
}
}
}
}
Console.ReadKey();
}
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
boolean successful = false;
int32 tries = 5;
Console.ForegroundColor = ConsoleColor.Green;
label1:
Do
{
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
successful = true;
}
}
if (!successful)
{
tries--;
Console.Clear();
Console.WriteLine("Invalid");
if (tries > 1)
{
Console.WriteLine("Have " + tries + " attempts left");
}
ElseIf (tries == 1)
{
Console.WriteLine("Have only one more attempt left");
}
Else
{
Console.WriteLine("Maximum number of tries exceed");
Console.WriteLine("Goodbye");
}
}
} While(!successful && Tries > 0);
}
}
Everytime you get the wrong input, you remaking your count int n = 5;
so everytime you have 5 tries left.
What you can do is to declare your count outside of the static void Main(string args[]) method
just like:
int n =5;
static void Main(string args[])
{
}
you problems are the following nested if-contitions
if (obj.getName() == "niit")
{
if (obj.getPass() == "1234")
{
Console.WriteLine("welcome");
}
}
else
{
\\...
}
If the username is correct and the pass not, it wont enter the else branch.
a better solution to ask for input until it is valid id a do ... while loop
Following example has a lot of improvements over yours.
static void Main(string[] args)
{
demo obj = new demo();
string uname, pass;
Console.ForegroundColor = ConsoleColor.Green;
int maxTries;
int tries = maxTries = 5;
do
{
if (tries != maxTries)//second and more
{
Console.Clear();
Console.WriteLine("Invalid");
Console.Write("\n\t" + tries + " Tries left");
Console.WriteLine("\n\n\n\tTry again? (y/n)");
string input;
do
{
input = Console.ReadLine();
} while (input != "y" && input != "n");
if (input == "n")
{
return; // exit the program
}
}
Console.Clear();
Console.WriteLine("Enter username");
uname = Console.ReadLine();
Console.WriteLine("Enter Password");
pass = Console.ReadLine();
obj.setName(uname);
obj.setPass(pass);
tries--;
} while (obj.getName() != "niit" || obj.getPass() != "1234");
Console.WriteLine("Wellcome");
}
PS: Classes should start with a capital letter.
goto is a relict of old times, it will mess with your programm structure and make things more complicated than they are. The only propper use i know is for fallthrough in switches, which also is needed only in rare cases.
A madeup one would be:
string vehicleType = "car";
switch(vehicleType)
{
case "truck":
Console.WriteLine("two wheeles and");
goto case "car";
case "car":
Console.WriteLine("two wheeles and");
goto case "motor cycle";
case "motor cycle":
Console.WriteLine("two wheeles");
break;
case "boat":
Console.WriteLine("no wheeles");
break;
}

Categories

Resources