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.");
}
Related
guys I just want some help. Sorry, I'm a newbie in C# programming. And my problem is that when I enter a value let say I enter 2, I want to print out: (Inserted so far: 0 out of 23.) But what happens is it shows the same value of soda which is 30 instead of 23.
namespace VendingMachine
{
class Program
{
static void Main(string[] args)
{
int itemPrice = 0;
int moneyAvailable = 0;
int change = 0;
int soda = 30;
int juice = 23;
int water = 15;
string userChoice;
// Menu
Console.WriteLine();
Console.WriteLine("1. Soda = P30");
Console.WriteLine("2. Juice = P23");
Console.WriteLine("3. Water = P15");
Console.WriteLine("4. Exit");
Console.WriteLine();
// Values entered by the user
Console.Write("Your choice: ");
userChoice = Console.ReadLine();
Console.WriteLine("================================");
// THE MAIN PROBLEM
if (itemPrice < soda)
{
Console.WriteLine($"Inserted so far: P0 out of P{soda}");
}
Console.Write("Enter the amount of Money!: P");
moneyAvailable = int.Parse(Console.ReadLine());
switch (userChoice)
{
case "1":
itemPrice = itemPrice + soda;
break;
case "2":
itemPrice = itemPrice + juice;
break;
case "3":
itemPrice = itemPrice + water;
break;
default:
Console.WriteLine("Invalid. Choose 1, 2 or 3.");
break;
}
You are using string interpolation with wrong variable name
if (itemPrice < soda)
{
Console.WriteLine($"Inserted so far: P0 out of P{itemPrice}");
// ^^^^^^^^^^ Problem is here
}
Instead of printing value of soda everytime you should print value of itemPrice.
This print statement with if condition should goes to end of switch statement
Something like,
Console.Write("Enter the amount of Money!: P");
moneyAvailable = int.Parse(Console.ReadLine());
switch (userChoice)
{
case "1":
itemPrice = itemPrice + soda;
break;
case "2":
itemPrice = itemPrice + juice;
break;
case "3":
itemPrice = itemPrice + water;
break;
default:
Console.WriteLine("Invalid. Choose 1, 2 or 3.");
break;
}
if (itemPrice < soda)
{
Console.WriteLine($"Inserted so far: P0 out of P{itemPrice}");
}
Wrong variable in the string output: {soda} instead of {itemPrice}
In your case, you have to check if (itemPrice < soda) after switch (userChoice)
This is what you wanted to do:
class Program
{
static void Main(string[] args)
{
List<Item> items = new List<Item>()
{
new Item
{
Name = "Soda",
Price = 30
},
new Item
{
Name = "Juice",
Price = 23
},
new Item
{
Name = "Water",
Price = 15
}
};
while (true)
{
//MENU
Log("Available Items:");
for(int i = 0; i < items.Count; i++)
{
Log("{0}. {1} = P{2}", i, items[i].Name, items[i].Price);
}
Console.WriteLine();
bool isInputValid = false;
string userChoice = string.Empty;
int chosenIndex = 0;
while (isInputValid == false)
{
try
{
Log("Choose your Item:");
userChoice = Console.ReadLine();
chosenIndex = int.Parse(userChoice);
if(chosenIndex < 0 || chosenIndex >= items.Count)
{
throw new ArgumentOutOfRangeException();
}
isInputValid = true;
}
catch
{
Log("Invalid choice!");
}
}
Item chosenItem = items[chosenIndex];
bool isPriceReached = false;
string userInsertedMoney = string.Empty;
int insertedMoney = 0;
while (isPriceReached == false)
{
try
{
Log("P{0} of P{1} needed Money for {2} inserted, waiting for more...", insertedMoney, chosenItem.Price, chosenItem.Name);
userInsertedMoney = Console.ReadLine();
insertedMoney += int.Parse(userInsertedMoney);
isPriceReached = insertedMoney >= chosenItem.Price;
}
catch
{
Log("Invalid money!");
}
}
Log("Here is your {0} with a rest of {1} money.{2}", chosenItem.Name, insertedMoney - chosenItem.Price, Environment.NewLine);
}
}
private static void Log(string message, params object[] args)
{
Console.WriteLine(string.Format(message, args));
}
}
public class Item
{
public string Name { get; set; }
public int Price { get; set; }
}
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");
}
}
}
}
}
hey i am doing BIT(bachelor of information technology) and I have read from a text file that has 20 lines and it is split by ',' what I am trying to do is get the and I am trying to find the cow that has the most milk in the switch menu I have done the search by ID number but I just can't get my head around the cow that produces the most milk from that text file
class Program
{
static void Main(string[] args)
{
Livestock[] animals = new Livestock[20];
int counter = 0;
string myLine;
string[] words;
TextReader tr = new StreamReader("S:/BIT694/livestock.txt");
while ((myLine = tr.ReadLine()) != null)
{
words = myLine.Split(',');
int ID = int.Parse(words[0]);
string LivestockType = words[1];
int YearBorn = int.Parse(words[2]);
double CostPerMonth = double.Parse(words[3]);
double CostOfVaccination = double.Parse(words[4]);
double AmountMilk = double.Parse(words[5]);
if (LivestockType == "Cow")
{
Cow newCow = new Cow(ID, "Cow", YearBorn, CostPerMonth, CostOfVaccination, AmountMilk);
animals[counter] = newCow;
}
else if (LivestockType == "Goat")
{
Goat newGoat = new Goat(ID, "Goat", YearBorn, CostPerMonth, CostOfVaccination, AmountMilk);
animals[counter] = newGoat;
}
counter++;
}
int choice;
for (;;)
{
do
{
Console.WriteLine("--------Menu--------"); // The menue Title
Console.WriteLine();
Console.WriteLine("1) Display livestock information by ID"); // Display the livestock by ID number
Console.WriteLine("2) Display cow that produced the most milk"); // Displays the cow that porduces the most milk
Console.WriteLine("3) Display goat that produced the least amount of milk"); // Displays the goat that produces the least amount of milk
Console.WriteLine("4) Calculate farm profit"); // Calculates the farm profit
Console.WriteLine("5) Display unprofitable livestock"); // Displays the unprofitable livestock
Console.WriteLine("0) Exit"); // Exits the program
Console.WriteLine();
Console.Write("Enter an option: ");
choice = int.Parse(Console.ReadLine());
} while (choice < 0 || choice > 5);
if (choice == 0) break;
Console.WriteLine("\n");
switch(choice)
{
case 1:
Console.Write("Enter livestock ID: ");
int input = int.Parse(Console.ReadLine());
// Find animal by id
Livestock livestock = null;
for(int i = 0; i < 20; i++)
{
if(animals[i].iD == input)
{
livestock = animals[i]; // Get the animal
}
}
if(livestock != null)
{
livestock.displayInfo();
} else
{
Console.WriteLine("ID not found"); // Invaild ID
}
break;
case 2:
Console.WriteLine("Cow that produced the most Milk:");
break;
case 3:
Console.WriteLine("Goat that produced the least amount of milk:");
break;
case 4:
Console.WriteLine("Calculateion of farm profit:");
break;
case 5:
Console.WriteLine("Livestock that are not profitable:");
break;
case 0:
Environment.Exit(0);
break;
default:
Console.WriteLine("The Option that you have entered is invalid please try again");
break;
}
Console.ReadLine();
}
}
}
public class Livestock
{
private int ID; //ID Number of livestock
private string LivestockType; //Value is either "Cow" or "Goat"
private int YearBorn; //Year of birth with format YYYY (i.e. 2014)
private double CostPerMonth; //The cost per month
private double CostOfVaccination; //Annual vaccination cost
private double AmountMilk; //The amount of milk produced per day in liters
public int iD { get { return ID; } }
public string livestockType { get { return LivestockType; } }
public double costPerMonth { get { return CostPerMonth; } }
public Livestock(int ID, string LivestockType,int YearBorn,double CostPerMonth,double CostOfVaccination,double AmountMilk)
{
this.ID = ID;
this.LivestockType = LivestockType;
this.YearBorn = YearBorn;
this.CostPerMonth = CostPerMonth;
this.CostOfVaccination = CostOfVaccination;
this.AmountMilk = AmountMilk;
}
public void displayInfo()
{
Console.WriteLine();
Console.WriteLine(LivestockType);
Console.WriteLine("ID:\t\t\t {0}",iD);
Console.WriteLine("Year Born:\t\t {0}",YearBorn);
Console.WriteLine("Cost Per Month\t\t ${0}",CostPerMonth);
Console.WriteLine("Cost Of Vaccination:\t ${0}",CostOfVaccination);
Console.WriteLine("Milk Per Day:\t\t {0}liters",AmountMilk);
return;
}
}
class Cow : Livestock
{
public Cow(int ID, string LivestockType, int YearBorn, double CostPerMonth, double CostOfVaccination, double AmountMilk) : base(ID, LivestockType, YearBorn, CostPerMonth, CostOfVaccination, AmountMilk)
{
}
}
you will see case 1 is done I just need to do the same for case 2.
You have declared AmountMilk with a private access specifier and it doesn't have a getter.
Assuming you are using C# 3 or greater, you can use automatic properties, so that you can define properties like
public string SomeProperty { get; set; }
The compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
Livestock maxCow = animals.Where(animal => animal.LivestockType == "Cow").OrderByDescending(animal => animal.AmountMilk).FirstOrDefault();
The above code uses a Linq expression,
animals.Where(animal => animal.LivestockType == "Cow"
gets all the animals of LiveStockType "Cow" on which we do a descending sort based on the AmountMilk property and FirstOrDefault returns the first element in the sorted collection, if there is no such element it returns null.
The full code:
static void Main(string[] args)
{
Livestock[] animals = new Livestock[20];
int counter = 0;
string myLine;
string[] words;
TextReader tr = new StreamReader("S:/BIT694/livestock.txt");
while ((myLine = tr.ReadLine()) != null)
{
words = myLine.Split(',');
int ID = int.Parse(words[0]);
string LivestockType = words[1];
int YearBorn = int.Parse(words[2]);
double CostPerMonth = double.Parse(words[3]);
double CostOfVaccination = double.Parse(words[4]);
double AmountMilk = double.Parse(words[5]);
if (LivestockType == "Cow")
{
Cow newCow = new Cow(ID, "Cow", YearBorn, CostPerMonth, CostOfVaccination, AmountMilk);
animals[counter] = newCow;
}
else if (LivestockType == "Goat")
{
Goat newGoat = new Goat(ID, "Goat", YearBorn, CostPerMonth, CostOfVaccination, AmountMilk);
animals[counter] = newGoat;
}
counter++;
}
int choice;
for (;;)
{
do
{
Console.WriteLine("--------Menu--------"); // The menue Title
Console.WriteLine();
Console.WriteLine("1) Display livestock information by ID"); // Display the livestock by ID number
Console.WriteLine("2) Display cow that produced the most milk"); // Displays the cow that porduces the most milk
Console.WriteLine("3) Display goat that produced the least amount of milk"); // Displays the goat that produces the least amount of milk
Console.WriteLine("4) Calculate farm profit"); // Calculates the farm profit
Console.WriteLine("5) Display unprofitable livestock"); // Displays the unprofitable livestock
Console.WriteLine("0) Exit"); // Exits the program
Console.WriteLine();
Console.Write("Enter an option: ");
choice = int.Parse(Console.ReadLine());
} while (choice < 0 || choice > 5);
if (choice == 0) break;
Console.WriteLine("\n");
switch (choice)
{
case 1:
Console.Write("Enter livestock ID: ");
int input = int.Parse(Console.ReadLine());
Livestock livestock = animals.Where(animal => animal.ID == input).ToList().FirstOrDefault();
if (livestock != null)
{
livestock.displayInfo();
}
else
{
Console.WriteLine("ID not found"); // Invaild ID
}
break;
case 2:
Console.WriteLine("Cow that produced the most Milk:");
Livestock maxCow = animals.Where(animal => animal.LivestockType == "Cow").OrderByDescending(animal => animal.AmountMilk).FirstOrDefault();
if (maxCow != null)
maxCow.displayInfo();
else
Console.WriteLine("No cow");
break;
case 3:
Console.WriteLine("Goat that produced the least amount of milk:");
break;
case 4:
Console.WriteLine("Calculateion of farm profit:");
break;
case 5:
Console.WriteLine("Livestock that are not profitable:");
break;
case 0:
Environment.Exit(0);
break;
default:
Console.WriteLine("The Option that you have entered is invalid please try again");
break;
}
Console.ReadLine();
}
}
}
public class Livestock
{
public int ID { get; set; } //ID Number of livestock
public string LivestockType {get; set;} //Value is either "Cow" or "Goat"
public int YearBorn { get; set; } //Year of birth with format YYYY (i.e. 2014)
public double CostPerMonth { get; set; }//The cost per month
public double CostOfVaccination { get; set; } //Annual vaccination cost
public double AmountMilk { get; set; } //The amount of milk produced per day in liters
public Livestock(int ID, string LivestockType, int YearBorn, double CostPerMonth, double CostOfVaccination, double AmountMilk)
{
this.ID = ID;
this.LivestockType = LivestockType;
this.YearBorn = YearBorn;
this.CostPerMonth = CostPerMonth;
this.CostOfVaccination = CostOfVaccination;
this.AmountMilk = AmountMilk;
}
public void displayInfo()
{
Console.WriteLine();
Console.WriteLine(LivestockType);
Console.WriteLine("ID:\t\t\t {0}", iD);
Console.WriteLine("Year Born:\t\t {0}", YearBorn);
Console.WriteLine("Cost Per Month\t\t ${0}", CostPerMonth);
Console.WriteLine("Cost Of Vaccination:\t ${0}", CostOfVaccination);
Console.WriteLine("Milk Per Day:\t\t {0}liters", AmountMilk);
return;
}
}
LINQ reference
Because you didn't provide your "Cow" class I have to do some fantasy-code inbetween.
case 2:
Cow cowWithBestMilk; //Used to save the cow with the most milk production
///Lets Search
for( int i = 0; i < animals.Count; ++i)
{
//check lifestock, but only cows
if( LivestockType == "Cow" )
{
//Amount to check of my livestock
double livestockMilk = animals[i].getMilkAmount(); //<-- fantasy code, you have to acces here the AmountMilk of your cow
if(cowWithBestMilk != null)
{
//check if the cow from the lifestock got more milk than the other cow
if( livestockMilk > cowWithBestMilk.getMilkAmount() ) //<-- you can use >= instead of > if you want to have the last cow with the same amount
{
cowWithBestMilk = animals[i];
}
}
else
{
//there was no other cow until now
cowWithBestMilk = animals[i];
}
} //if type cow
} //for
if( cowWithBestMilk != null)
{
Console.WriteLine("Cow that produced the most Milk:" + cowWithBestMilk.getHerIdAsString() ); //<--fantasy code here
}
else
{
Console.WriteLine("Who let the cows out?");
}
break;
So what are we doing there.
First we declare cowWithBestMilk and in the loop we iterate over all livestock and overwrite our cowWithBestMilk when in the iteration over the livestock a cow is found AND it produced a higher amount of milk then our cow(WithBestMilk) from the previous iteration.
At the end when doing the console output, the case that our livestock didn't had any cow is covered by an alternate output.
I hope this helps a little bit.
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;
}
This code throws a Format Exception when a wrong input is input by the user at the conversion of the string to int. It also doesn't reach the desired output of "All first class seats have been booked" when 32 tickets have been sold, it just throws an index out of range exception. Any help with this would be greatly appreciated. Thanks.
class FirstClassCompartment
{
public void FirstClassTickets()
{
bool[] seats = new bool[32];
List<int> seatsBooked = new List<int>();
int completeBooking = 0;
bool quit = false;
string ticketAmount = "";
int firstClassSeat = 0;
int convertedTicketAmount;
{
Groups firstClass = new Groups();
Console.Clear();
Console.WriteLine("\nWelcome to the First Class booking menu");
Console.WriteLine("");
Console.WriteLine("Please enter the amount of tickets you would like to book");
ticketAmount = Console.ReadLine();
Console.Clear();
Console.WriteLine("\nFirst Class booking menu");
convertedTicketAmount = Convert.ToInt32(ticketAmount);
ticketAmount = firstClass.NumberInGroupFirstClassWest;
}
do
{
Console.Clear();
Console.WriteLine("\nFirst Class booking menu");
Console.WriteLine("");
Console.WriteLine("Please press 1 to complete your first class booking");
completeBooking = Int32.Parse(Console.ReadLine());
switch (completeBooking)
{
case 1:
if (seatsBooked.Count == 0)
{
firstClassSeat++;
seats[firstClassSeat] = true;
seatsBooked.Add(firstClassSeat);
}
else
{
do
{
firstClassSeat++;
if (!seatsBooked.Contains(firstClassSeat))
{
seats[firstClassSeat] = true;
}
}
while (seatsBooked.Contains(firstClassSeat) && seatsBooked.Count < 32);
if (seatsBooked.Count < 32)
{
seatsBooked.Add(firstClassSeat);
}
}
if (seatsBooked.Count > 32)
{
Console.WriteLine("All seats for first class have been booked");
Console.WriteLine("Please press enter to continue...");
}
else
{
Console.WriteLine("Your seat: {0}", firstClassSeat + 1);
Console.WriteLine("Please press enter to continue...");
}
Console.ReadLine();
break;
default:
Console.WriteLine("\nPlease enter a valid input");
quit = true;
break;
}
} while (!quit);
}
}
You need to use Int32.TryParse and check the returned bool.
Look at the logic in you switch statement, you only handle a booking of 1. What if the user books 2 seats?
Edit: Sorry, just realised that switch statement is to handle the menu, not number of bookings
Do you need a list of ints, as well as an array of bools in order to track how many seats have been booked? Couldn't you just use a plain old int, e.g. numberOfSeatsBooked? Then you can do numberOfSeatsBooked += convertedTicketAmount;
I would do this very differently. You should have a class for seats containing a boolean for booked and iterate that rather than a random array of books that may or may not be linked to a random list of booked seats and a number of seats booked. Here's a small example:
public class Seat
{
public int SeatNo { get; set; }
public bool FirstClass { get; set ; }
public bool Booked { get; set; } // could actually be an instance of a booking info class including name and ticket id, etc.
}
public class Flight
{
public List<Seat> Seats = new List<Seat>();
private int _lastSeat = 0;
public void AddSeats(int num, bool firstClass)
{
for (int i = 0; i < num; i++)
{
_lastSeat++;
Seats.Add(new Seat { SeatNo = num, FirstClass = firstClass });
}
}
public int BookNextAvailableSeat(bool firstClass)
{
foreach (Seat seat in Seats.AsQueryable().Where(x => x.FirstClass == firstClass)
{
if (!seat.Booked)
{
seat.Booked = true;
return seat.SeatNo;
}
}
return null;
}
}
Then your:
case 1:
int booking = flight.BookNextAvailableSeat(true);
if (booking != null)
Console.WriteLine("Your seat: {0}", booking);
else
Console.WriteLine("All seats for first class have been booked");
Console.WriteLine("Please press enter to continue...");
break;
Of course you need to instantiate flight and add the 32 seats using:
Flight flight = new Flight();
flight.AddSeats(32, true);