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);
Related
In this code, I try to code to keep customer data to keep in an array list. I need to keep first name, last name, contact number, and payment method.
public static void Rent()
{
WriteLine("Enter your first name");
input_fname = ReadLine();
WriteLine("Enter your last name");
input_lname = ReadLine();
WriteLine("Enter your contact number");
input_phone = ReadLine();
WriteLine("Enter your payment method");
input_payment = ReadLine();
ArrayList arr_cust = new ArrayList();
for (int i = 0; i <= arr_cust.Count; i++)
{
arr_cust.Add(input_fname + input_lname + input_phone + input_payment);
}
WriteLine("Pease enter 1 to return to previous menu and 0 to exit");
int input = Convert.ToInt32(ReadLine());
bool exit = false;
while (exit == false)
{
if (input == 1)
{
Main();
}
else if (input == 0)
{
WriteLine("Thank you for use Rental E-Bike System");
System.Environment.Exit(0);
}
else
{
}
}
}
My problem is when I put all of the value that i need to keep and after the I put 1 to back to main page. Next, I open Rent page again to put the second of value to keep in array list. Next step, I need to show data which I keep in array list.
Your Rent function creates a new instance of ArrayList each time it is invoked and that is why arr_cust is always empty and the only value it has is the one you insert within the Rent function.
Instead of initializing arr_cust within Rent you can initialize it as a static field outside of the function so it retains the previous values.
Also you do not need the for loop to insert your data. You are inserting only once and with the for loop you are going to get N duplicates of that entry. N being the previous item count.
public static ArrayList arr_cust = new ArrayList();
public static void Rent(ArrayList arr_cust)
{
WriteLine("Enter your first name");
input_fname = ReadLine();
WriteLine("Enter your last name");
input_lname = ReadLine();
WriteLine("Enter your contact number");
input_phone = ReadLine();
WriteLine("Enter your payment method");
input_payment = ReadLine();
arr_cust.Add(input_fname + input_lname + input_phone + input_payment);
WriteLine("Pease enter 1 to return to previous menu and 0 to exit");
int input = Convert.ToInt32(ReadLine());
bool exit = false;
while (exit == false)
{
if (input == 1)
{
Main();
}
else if (input == 0)
{
WriteLine("Thank you for use Rental E-Bike System");
System.Environment.Exit(0);
}
}
}
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; }
}
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.");
}
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.
I am creating a random number guessing game where the user sets the maximum number they want to guess from. I have figured out most of the code, the problem that I seem to be getting is that after setting the maximum number and beginning to guess the answer is always 0. Any tips on how to adjust my code so that the answer is a number within the range and not 0?
class Program
{
public static int SelectedNumber = 0;
public static Random ran = new Random();
public static bool GameOver = false;
public static int UserMaxValue = 0;
public static string decision;
static void Main(string[] args)
{
int UserNumber;
SelectedNumber = ran.Next(0, UserMaxValue);
do
{
Console.WriteLine("What is the maximum number you want to guess from?");
UserMaxValue = Convert.ToInt32(Console.ReadLine());
do
{
Console.WriteLine("Select a number between 1 and {0}!", UserMaxValue);
UserNumber = Convert.ToInt32(Console.ReadLine());
GuessNumber(UserNumber);
} while (GameOver == false);
} while (GameOver == false);
}
public static void GuessNumber(int UserNumber)
{
if (UserNumber < SelectedNumber)
Console.WriteLine("Your number is wrong, please try again!");
else if (UserNumber > SelectedNumber)
Console.WriteLine("Your Number is wrong, please try again!");
//else if (UserNumber == 0)
// Console.WriteLine("Your Number is wrong, please try again!");
else
{
Console.WriteLine("Yay! You got the right number. Do you want to play again? (y/n) ", decision);
decision = Console.ReadLine();
if (decision == "n")
GameOver = true;
else
do
{
Console.WriteLine("What is the maximum number you want to guess from?");
UserMaxValue = Convert.ToInt32(Console.ReadLine());
do
{
Console.WriteLine("Select a number between 1 and {0}!", UserMaxValue);
UserNumber = Convert.ToInt32(Console.ReadLine());
GuessNumber(UserNumber);
} while (GameOver == false);
} while (GameOver == false);
}
}
}
}
You have the following lines, in this order (I'm omitting the rest in between):
public static int UserMaxValue = 0;
// ...
SelectedNumber = ran.Next(0, UserMaxValue);
// ...
Console.WriteLine("What is the maximum number you want to guess from?");
UserMaxValue = Convert.ToInt32(Console.ReadLine());
You have to ask the user for UserMaxValue before you can correctly set SelectedNumber.
Had to do some corrections on your code. Added some comments for the changes.
You better add error handling on the user input.
UPDATE: Added error handling for invalid input.
class Program
{
public static int SelectedNumber = 0;
public static Random ran = new Random();
public static bool GameOver = false;
public static int UserMaxValue = 0;
static void Main(string[] args)
{
int UserNumber = 0;
bool playAgain = false;
do
{
bool isUserMaxValueValid = false;
do
{
Console.WriteLine("What is the maximum number you want to guess from?");
isUserMaxValueValid = int.TryParse(Console.ReadLine(), out UserMaxValue);
} while (!isUserMaxValueValid);
SelectedNumber = ran.Next(1, UserMaxValue); // Re-assign SelectedNumber for every new max number input. Random number start changed to 1 to avoid 0 value for SelectedNumber
do
{
bool isUserNumberValid = false;
do
{
Console.WriteLine("Select a number between 1 and {0}!", UserMaxValue);
isUserNumberValid = int.TryParse(Console.ReadLine(), out UserNumber);
} while (!isUserNumberValid);
playAgain = GuessNumber(UserNumber);
// I changed GameOver to see if the guessing portion is finished or not
} while (!GameOver); // You don't need to use GameOver == false
} while (playAgain); // Check if user wants to play again or not
}
public static bool GuessNumber(int UserNumber)
{
if (UserNumber != SelectedNumber)
{
GameOver = false;
Console.WriteLine("Your number is wrong, please try again!");
}
else
{
GameOver = true;
bool isPlayAgainValid = false;
Console.WriteLine("Yay! You got the right number. Do you want to play again? (y/n)");
do
{
string decision = Console.ReadLine();
if (decision.Equals("n", StringComparison.InvariantCultureIgnoreCase))
{
return false;
}
else if (decision.Equals("y", StringComparison.InvariantCultureIgnoreCase))
{
break;
}
if(!isPlayAgainValid)
{
Console.WriteLine("Please enter y or n only.");
}
} while (!isPlayAgainValid);
// I removed redundant code
}
return true;
}
}