I am trying to make a simple menu where I can choose with the arrows on the keyboard. I can run the code and the program doesn't give any errors, however I can not choose with the arrows and nothing happens if I press Enter, the choice always remains on the first choice (New customer). That will say, It always stays like this:
Hello and welcome! please choose type of registration:
*New customer <--
New staff
Service
Reparation
Garantie
My code this far is:
using System;
namespace uppdrag_2.cs
{
class Program
{
static void Main(string[] args)
{
string[] menuOptions = new string[] {"New customer\t", "New staff\t", "Serivce\t", "Reparation", "Garantie" };
int menuSelect = 0;
while (true)
{
Console.Clear();
Console.CursorVisible = false;
Console.WriteLine("Hello and welcome! Please choose type of registration:");
if (menuSelect == 0)
{
Console.WriteLine("* " + menuOptions[0] + "<--");
Console.WriteLine(menuOptions[1]);
Console.WriteLine(menuOptions[2]);
Console.WriteLine(menuOptions[3]);
Console.WriteLine(menuOptions[4]);
Console.ReadLine();
}
else if (menuSelect == 1)
{
Console.WriteLine(menuOptions[0]);
Console.WriteLine("* " + menuOptions[1] + "<--");
Console.WriteLine(menuOptions[2]);
Console.WriteLine(menuOptions[3]);
Console.WriteLine(menuOptions[4]);
Console.ReadLine();
}
else if (menuSelect == 2)
{
Console.WriteLine(menuOptions[0]);
Console.WriteLine(menuOptions[1]);
Console.WriteLine("* " + menuOptions[2] + "<--");
Console.WriteLine(menuOptions[3]);
Console.WriteLine(menuOptions[4]);
Console.ReadLine();
}
else if (menuSelect == 3)
{
Console.WriteLine(menuOptions[0]);
Console.WriteLine(menuOptions[1]);
Console.WriteLine(menuOptions[2]);
Console.WriteLine("* " + menuOptions[3] + "<--");
Console.WriteLine(menuOptions[4]);
Console.ReadLine();
}
else if (menuSelect == 4)
{
Console.WriteLine(menuOptions[0]);
Console.WriteLine(menuOptions[1]);
Console.WriteLine(menuOptions[2]);
Console.WriteLine(menuOptions[3]);
Console.WriteLine("* " + menuOptions[4] + "<--");
Console.ReadLine();
}
var keyPressed = Console.ReadKey();
if (keyPressed.Key == ConsoleKey.DownArrow && menuSelect != menuOptions.Length - 1)
{
menuSelect++;
}
else if (keyPressed.Key == ConsoleKey.UpArrow && menuSelect >= 1)
{
menuSelect--;
}
else if (keyPressed.Key == ConsoleKey.Enter)
{
switch (menuSelect)
{
case 0:
Newcustomer();
break;
case 1:
NewStaff();
break;
case 2:
Service();
break;
case 3:
Reparation();
break;
case 4:
Garantie();
break;
}
}
}
}
public static void Newcustomer(){
Console.WriteLine("You have chosen to registrate a new customer!");
Console.WriteLine("Please enter name of customer:");
string name = Console.ReadLine();
Console.WriteLine("Enter car brand:");
string carBrand = Console.ReadLine();
Console.WriteLine("Enter model of car");
string model = Console.ReadLine();
Console.WriteLine("Enter year model");
string yearModel = Console.ReadLine();
Console.WriteLine("Enter how many km the car has been driven");
string km = Console.ReadLine();
Console.WriteLine("Registration compleated!");
Console.WriteLine("You have registered a new customer! You have registrered" + " " + name + " " + "with the carbrand" + carBrand + " " + "of model" + " " + model + " " + "form year" + " " + yearModel + " " + "That has been driven" + " " + km + "km.");
Console.ReadKey();
}
public static void NewStaff(){
Console.WriteLine("You have chosen to registrer a new staffmember!");
Console.WriteLine("Please enter name of staffmember:");
string staffName = Console.ReadLine();
Console.WriteLine("Enter age:");
string ageStaff = Console.ReadLine();
Console.WriteLine("Enter work position of the new staffmember:");
string position = Console.ReadLine();
Console.WriteLine("Enter type of contract:");
string contract = Console.ReadLine();
Console.WriteLine("Enter date of the workers first day:");
string start = Console.ReadLine();
Console.WriteLine("Enter date of the workrs last day:");
string end = Console.ReadLine();
Console.WriteLine("Registration compleated!");
Console.WriteLine("You have registrered a new staffmember! The following information has been registered:\t" + "name: " + staffName + "\t" + "age: " + ageStaff + "\t" + "position: " + position + "\t" + "Contract: " + contract + "\t" + "First day: " + start + "\t" + "Last day: " + end);
Console.ReadKey();
}
public static void Service(){
Console.WriteLine("Please enter type of service:");
string service = Console.ReadLine();
Console.WriteLine("Enter the name of an registered customer. If customer is not already registered, please press Enter to return to menu and choose `New customer`");
string customerservice = Console.ReadLine();
Console.WriteLine("Enter staffmember responsible for this matter. If staffmember is new, please press Enter to return to the menu and choose ``New staff`");
string servicestaff = Console.ReadLine();
Console.WriteLine("Enter staring day of service:");
string serviceStart = Console.ReadLine();
Console.WriteLine("Enter deadline of servicematter:");
string deadline = Console.ReadLine();
Console.WriteLine("Service matter registrered!");
Console.WriteLine("Following information has been registrered:\t" + "Service matter: " + service + "\t" + "Customer: " + customerservice + "\t" + "Staff member responsible: " + servicestaff + "\t" + "Startdate of service matter: " + serviceStart + "\t" + "Deadline: " + deadline);
Console.ReadKey();
}
public static void Reparation(){
Console.WriteLine("You have choosen to registrer a reparation matter!");
Console.ReadLine();
Console.ReadKey();
}
public static void Garantie(){
Console.WriteLine("You have choosen to registrate a garantie matter!");
Console.WriteLine();
Console.ReadKey();
}
}
}
Anyone who could help me figure out what I`ve done wrong?
You can shorten your menu code quite a bit by using a for loop and a ternary if statement:
static void Main(string[] args)
{
string[] menuOptions = new string[] { "New customer\t", "New staff\t", "Serivce\t", "Reparation\t", "Garantie\t" };
int menuSelect = 0;
while (true)
{
Console.Clear();
Console.CursorVisible = false;
Console.WriteLine("Hello and welcome! Please choose type of registration:");
for (int i = 0; i < menuOptions.Length; i++)
{
Console.WriteLine((i == menuSelect ? "* " : "") + menuOptions[i] + (i == menuSelect ? "<--" : ""));
}
var keyPressed = Console.ReadKey();
if (keyPressed.Key == ConsoleKey.DownArrow && menuSelect != menuOptions.Length - 1)
{
menuSelect++;
}
else if (keyPressed.Key == ConsoleKey.UpArrow && menuSelect >= 1)
{
menuSelect--;
}
else if (keyPressed.Key == ConsoleKey.Enter)
{
switch (menuSelect)
{
case 0:
Newcustomer();
break;
case 1:
NewStaff();
break;
case 2:
Service();
break;
case 3:
Reparation();
break;
case 4:
Garantie();
break;
}
}
}
}
public static void Newcustomer()
{
Console.WriteLine("New Customer ...");
Console.Write("Press Enter to Continue");
Console.ReadLine();
}
public static void NewStaff()
{
Console.WriteLine("New Staff ...");
Console.Write("Press Enter to Continue");
Console.ReadLine();
}
public static void Service()
{
Console.WriteLine("Service ...");
Console.Write("Press Enter to Continue");
Console.ReadLine();
}
public static void Reparation()
{
Console.WriteLine("Reparation ...");
Console.Write("Press Enter to Continue");
Console.ReadLine();
}
public static void Garantie()
{
Console.WriteLine("Garantie ...");
Console.Write("Press Enter to Continue");
Console.ReadLine();
}
}
It works fine for me:
Related
I'm doing a school project and I really feel that I can acomplish what I want in my code, however I feel like i -always- repeat my code.
I have tried to put the switch cases into methods but haven't had any success though to out of scope.
I am beginner so sorry for the eyesore code!
However, if anyone have any tips for using methods or something else so I can clean up my code a little better.
So here is a bit of my code, this is the beginning branch of my menu.
I have translated the code roughly to english.
So this is a sub menu in the main method.
string[] flowers = { "Sunflower", "Coleus Tree", "Tomato" };
int[] plant = { 0, 0, 0 };
switch (menuInput03)
{
/////WATER PLANT////
case 1:
Console.Clear();
Console.WriteLine("Press SPACEBAR several times to water plant!");
if (plant[0] < 21)
{
for (int i = plant[0]; i < 21; i++)
{
var keyPressed = Console.ReadKey();
if (keyPressed.Key == ConsoleKey.Spacebar)
{
plant[0] = i;
Console.Clear();
Console.WriteLine("Press SPACEBAR several times to water plant!");
Console.WriteLine("\nWatering plant..");
Console.WriteLine("[" + flowers[0] + " " + plant[0] + "/100]");
}
}
while (true)
{
Console.Clear();
Console.WriteLine("Your plant has been watered!");
Console.WriteLine("[" + flowers[0] + " " + plant[0] + "/100]\n");
Console.WriteLine("To continue press ENTER.");
var keyPressed01 = Console.ReadKey();
if (keyPressed01.Key == ConsoleKey.Enter)
{
Console.Clear();
break;
}
else
{
Console.Clear();
}
}
}
else
{
break;
}
Console.Clear();
break;
case 2:
Console.Clear();
Console.WriteLine("Press SPACEBAR several times to remove weed!");
if (plant[0] > 19)
{
for (int i = plant[0]; i < 51; i++)
{
var keyPressed = Console.ReadKey();
if (keyPressed.Key == ConsoleKey.Spacebar)
{
plant[0] = i;
i++;
Console.Clear();
Console.WriteLine("Press SPACEBAR several times to remove weed!");
Console.WriteLine("\nRipping out weeds..");
Console.WriteLine("[" + flowers[0] + " " + plant[0] + "/100]");
}
}
while (true)
{
Console.Clear();
Console.WriteLine("Your plant has gotten it's weed removed!");
Console.WriteLine("[" + flowers[0] + " " + plant[0] + "/100]\n");
Console.WriteLine("To continue press ENTER.");
var keyPressed01 = Console.ReadKey();
if (keyPressed01.Key == ConsoleKey.Enter)
{
Console.Clear();
break;
}
else
{
Console.Clear();
}
}
}
Console.Clear();
break;`
I came up with the following; don't just copy-paste for school project without understanding what is going on. If some things are not clear do not hesitate to ask follow-up questions.
public record Action
{
public string Title { get; }
public int RequiredHealth { get; }
public string ActionMessage { get; }
public string CompletedMessage { get; }
private Action(string title, int requiredHealth, string actionMessage, string completedMessage)
{
Title = title;
RequiredHealth = requiredHealth;
ActionMessage = actionMessage;
CompletedMessage = completedMessage;
}
public static Action WaterPlant { get; } = new Action(
title: "Press SPACEBAR several times to water plant!",
requiredHealth: 20,
actionMessage: "Watering plant..",
completedMessage: "Your plant has been watered!");
public static Action RemoveWeed { get; } = new Action(
title: "Press SPACEBAR several times to remove weed!",
requiredHealth: 50,
actionMessage: "Ripping out weeds..",
completedMessage: "Your plant has gotten it's weed removed!");
}
static void Main()
{
string[] flowers = { "Sunflower", "Coleus Tree", "Tomato" };
int[] plant = { 0, 0, 0 };
for (var menuInput03 = 1; menuInput03 <= 2; menuInput03++)
{
var action = menuInput03 switch
{
1 => Action.WaterPlant,
2 => Action.RemoveWeed,
};
Console.Clear();
Console.WriteLine(action.Title);
while (plant[0] < action.RequiredHealth)
{
if (Console.ReadKey().Key != ConsoleKey.Spacebar)
{
Console.Write("\b \b");
continue;
}
plant[0]++;
Console.Clear();
Console.WriteLine(action.Title);
Console.WriteLine(action.ActionMessage);
Console.WriteLine($"[{flowers[0]} {plant[0]}/100]");
}
Console.Clear();
Console.WriteLine(action.CompletedMessage);
Console.WriteLine($"[{flowers[0]} {plant[0]}/100]");
Console.WriteLine("To continue press ENTER.");
while (Console.ReadKey().Key != ConsoleKey.Enter)
{
Console.Write("\b \b");
}
Console.Clear();
}
}
I'm new to writing code and I'm starting with a TicTacToe game to introduce myself. So far I have this:
namespace TicTacToe
{
class Program
{
static void Main(string[] args)
{
string square1 = " ";
string square2 = " ";
string square3 = " ";
string square4 = " ";
string square5 = " ";
string square6 = " ";
string square7 = " ";
string square8 = " ";
string square9 = " ";
bool playerIsX = true;
string symbol = "X";
while (true)
{
Console.WriteLine(" " + square1 + " | " + square2 + " | " + square3);
Console.WriteLine("-----------");
Console.WriteLine(" " + square4 + " | " + square5 + " | " + square6);
Console.WriteLine("-----------");
Console.WriteLine(" " + square7 + " | " + square8 + " | " + square9);
if (playerIsX == true)
{
Console.Write("X enter square: ");
}
else
{
Console.Write("O enter square: ");
}
string square = Console.ReadLine();
if (square == "1")
{
square1 = symbol;
}
else if (square == "2")
{
square2 = symbol;
}
else if (square == "3")
{
square3 = symbol;
}
else if (square == "4")
{
square4 = symbol;
}
else if (square == "5")
{
square5 = symbol;
}
else if (square == "6")
{
square6 = symbol;
}
else if (square == "7")
{
square7 = symbol;
}
else if (square == "8")
{
square8 = symbol;
}
else if (square == "9")
{
square9 = symbol;
}
if (square1 == square2 & square2 == square3)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
else if (square1 == square4 & square4 == square7)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
if (square4 == square5 & square5 == square6)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
if (square7 == square8 & square8 == square9)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
if (square2 == square5 & square5 == square8)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
if (square3 == square6 & square6 == square9)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
if (square1 == square5 & square5 == square9)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
if (square3 == square5 & square5 == square7)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
Console.Clear();
playerIsX = !playerIsX;
if (playerIsX == true)
{
symbol = "X";
}
else
{
symbol = "O";
}
}
}
}
}
I know it's beefy but I'm only trying to get a basic understanding so I can move on from there. Currently for the winning I compare three values, but since they're all spaces, at the start of the game multiple possibilities already trigger the win. Is there a way to exclude a value, say space?
Thanks.
In your specific situation, you have a common field in each if statement - a field is always evaluated twice as such:
if (square4 == square5 & square5 == square6)
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
square5 is evaluated against both square4, and square6, so we can definitely argue that if square5 is not equal to " ", this statement will not pass.
From there, you could easily just implement a quick check:
if (square4 == square5 & square5 == square6 && square5 != " ")
{
Console.Clear();
Console.WriteLine("You Win!");
Console.ReadLine();
break;
}
I would highly suggest you look into developing a more readable, and elegant piece of code for what you're doing though, good luck on your learning journey!
The quickest (not best) way to do it would be to check for a space in your comparison. That means this
if (square1 == square2 & square2 == square3)
would turn into
if (square1 == square2 & square2 == square3 & square3 != " ")
So I'm stuck again, I created a 'game choices' program that allows users to choose their 'skill' level. I have wrote all the code but the do loop on line 24 is causing issues. It will not loop when I choose a higher skill level than 4 or when I type 'n' in "Is this what you want (y/n)". Here is the code:
class Program
{
static void Main(string[] args)
{
string name;
int one = 1, two = 2, three = 3, four = 4;
int answer;
int tripalarm = 0;
string verification;
Console.WriteLine("What is your name?");
name = Convert.ToString(Console.ReadLine());
Console.WriteLine(name + ", there are 4 skill levels in this game:");
Console.WriteLine("1. Advanced" + Environment.NewLine + "2. Experienced" + Environment.NewLine + "3. Average"
+ Environment.NewLine + "4. Novice");
do
{
answer = 0;
Console.WriteLine("Which skill level do you choose?");
answer = Convert.ToInt32(Console.ReadLine());
if (answer >= 5)
{
Console.WriteLine("Sorry " + name + " you should choose between 1 and 4:");
}
else if (answer <= 4)
{
if (answer == one)
{
Console.WriteLine("Thank you " + name + ", you have choosen level one");
Console.WriteLine("Is this what you want? (y/n)");
verification = Convert.ToString(Console.ReadLine());
if (verification == "y")
{
Console.WriteLine("Good " + name + " you have chosen level one you can now start the game!");
}
else
{
tripalarm++;
}
}
else if (answer == two)
{
Console.WriteLine("Thank you " + name + ", you have choosen level two");
Console.WriteLine("Is this what you want? (y/n)");
verification = Convert.ToString(Console.ReadLine());
if (verification == "y")
{
Console.WriteLine("Good " + name + " you have chosen level two you can now start the game!");
}
else
{
tripalarm++;
}
}
else if (answer == three)
{
Console.WriteLine("Thank you " + name + ", you have choosen level three");
Console.WriteLine("Is this what you want? (y/n)");
verification = Convert.ToString(Console.ReadLine());
if (verification == "y")
{
Console.WriteLine("Good " + name + " you have chosen level three you can now start the game!");
}
else
{
tripalarm++;
}
}
else if (answer == four)
{
Console.WriteLine("Thank you " + name + ", you have choosen level four");
Console.WriteLine("Is this what you want? (y/n)");
verification = Convert.ToString(Console.ReadLine());
if (verification == "y")
{
Console.WriteLine("Good " + name + " you have chosen level four you can now start the game!");
}
else
{
tripalarm++;
}
}
}
} while (tripalarm == 0);
}
}
I have tried almost everything, changing the while value at the bottom does not change anything. It still loops when it is not supposed to.
Much help would be appreciated, thanks.
This simplifies your code a bit and should correct the bug:
static void Main(string[] args)
{
var levelSelected = false;
var answer = 0;
Console.WriteLine("What is your name?");
string name = Console.ReadLine();
Console.WriteLine($"{name}, there are 4 skill levels in this game:");
Console.WriteLine("1. Advanced");
Console.WriteLine("2. Experienced");
Console.WriteLine("3. Average");
Console.WriteLine("4. Novice");
while (!levelSelected)
{
Console.WriteLine("Which skill level do you choose?");
answer = Convert.ToInt32(Console.ReadLine());
switch (answer)
{
case 1:
case 2:
case 3:
case 4:
Console.WriteLine($"Thank you {name}, you have choosen level {answer}");
Console.WriteLine("Is this what you want? (y/n)");
levelSelected = Console.ReadLine() == "y";
break;
default:
Console.WriteLine($"Sorry {name} you should choose between 1 and 4:");
break;
}
}
Console.WriteLine($"Good {name} you have chosen level {answer} you can now start the game!");
var x = Console.ReadLine();
}
Note it still doesn't check that the user enters an integer for the level (if they don't it will cause an error) and anything other that "y" is treated as "n".
Okay, I am using an Automobile class that I have created myself. I am trying to use a List<Automobile>. I am trying to write this program that will use the List<Automobile> and storing the users input in my Automobile class. When I run my code and try to put more than one car in my List<Automobile>, it just overwrites the previous car that the user entered. I know that my code is a mess. I am completely new to using List<> and writing/reading files.
Just in case I was not very clear in my ramblings. I am trying to figure out why my List<Automobile> keeps getting over written when more than one car is wrote to the List<Automobile>.
Thank you in advance to anyone and everyone's help with me solving this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Exercise6_DealerVehicleInventory
{
class Program
{
static void Main(string[] args)
{
#region Variables/Constructors
var answer = "";
Automobile car = new Automobile();
List<Automobile> vehicle = new List<Automobile>();
#endregion
#region User Car Input
/* I might be able to put all of this in one big while loop that way I
* can have more than one vehicle wrote to this file at a time. */
Console.Write("Do you want to add a car?\nY for yes or N for no: ");
answer = Console.ReadLine();
while (answer == "Y" || answer == "y")
{
Console.Write("\nEnter the make of the car: ");
car.Make = Console.ReadLine();
Console.Write("Enter the model of the car: ");
car.Model = Console.ReadLine();
Console.Write("Enter the color of the car: ");
car.Color = Console.ReadLine();
Console.Write("Enter the year of the car: ");
car.Year = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the mileage of the car: ");
car.Mileage = Convert.ToInt32(Console.ReadLine());
vehicle.Add(car);
Console.Write("Do you want to add a car?\nY for yes or N for no: ");
answer = Console.ReadLine();
}
#endregion
#region Delete From In Memory
Console.Write("\nDo you want to delete a car?\nY for yes or N for no: ");
answer = Console.ReadLine();
if (answer == "Y" || answer == "y")
{
int i = 0;
int delEntry = 0;
foreach(Automobile automobile in vehicle)
{
Console.Write("#" + i + " = " + automobile.Make + " " + automobile.Model + " " + automobile.Color + " " + automobile.Year + " " + automobile.Mileage + "\n");
i++;
}
Console.WriteLine("\nWhat item number would you like to delete: ");
delEntry = Convert.ToInt32(Console.ReadLine());
vehicle.RemoveAt(delEntry);
}
#endregion
#region Write Data To File
Console.Write("\nDo you want to write this to a text file?\nY for yes or N for no: ");
answer = Console.ReadLine();
string mydocpath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (answer == "Y" || answer == "y") //(string.Equals("y", answer, StringComparison.CurrentCultureIgnoreCase))
{
using (StreamWriter sw = new StreamWriter(mydocpath + #"\Vehicle.txt"))
{
foreach (Automobile automobile in vehicle)
{
sw.WriteLine(automobile.Make + " " + automobile.Model + " " + automobile.Color + " " + automobile.Year + " " + automobile.Mileage);
}
}
}
else
{
Console.WriteLine("No data wrote to file: ");
}
#endregion
#region Update Vehicle File
Console.Write("\nWould you like to add another vehicle?\nY for yes or N for no: ");
answer = Console.ReadLine();
if (answer == "Y" || answer == "y")
{
StreamReader sr = new StreamReader(mydocpath + #"\Vehicle.txt");
String line = sr.ReadLine();
Console.Write("\n" + line);
while (answer == "Y" || answer == "y")
{
Console.Write("Enter the make of the car: ");
car.Make = Console.ReadLine();
Console.Write("Enter the model of the car: ");
car.Model = Console.ReadLine();
Console.Write("Enter the color of the car: ");
car.Color = Console.ReadLine();
Console.Write("Enter the year of the car: ");
car.Year = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the mileage of the car: ");
car.Mileage = Convert.ToInt32(Console.ReadLine());
vehicle.Add(car);
Console.Write("\nDo you want to delete a car?\nY for yes or N for no: ");
answer = Console.ReadLine();
if (answer == "Y" || answer == "y")
{
int i = 0;
int delEntry = 0;
foreach (Automobile automobile in vehicle)
{
Console.Write("#" + i + " = " + automobile.Make + " " + automobile.Model + " " + automobile.Color + " " + automobile.Year + " " + automobile.Mileage + "\n");
i++;
}
Console.WriteLine("\nWhat item number would you like to delete: ");
delEntry = Convert.ToInt32(Console.ReadLine());
vehicle.RemoveAt(delEntry);
}
Console.Write("\nDo you want to write this to a text file?\nY for yes or N for no: ");
answer = Console.ReadLine();
if (answer == "Y" || answer == "y") //(string.Equals("y", answer, StringComparison.CurrentCultureIgnoreCase))
{
using (StreamWriter sw = new StreamWriter(mydocpath + #"\Vehicle.txt", true))
{
foreach (Automobile automobile in vehicle)
{
sw.WriteLine(automobile.Make + " " + automobile.Model + " " + automobile.Color + " " + automobile.Year + " " + automobile.Mileage);
}
}
}
}
}
else
{
Console.WriteLine("Nothing else was added to the file.");
}
#endregion
Console.ReadLine();
}
}
}
Below is my Automobile class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise6_DealerVehicleInventory
{
class Automobile
{
private string _make;
public string Make
{
get { return _make; }
set { _make = value; }
}
private string _model;
public string Model
{
get { return _model; }
set { _model = value; }
}
private string _color;
public string Color
{
get { return _color; }
set { _color = value; }
}
private int _year;
public int Year
{
get { return _year; }
set { _year = value; }
}
private int _mileage;
public int Mileage
{
get { return _mileage; }
set { _mileage = value; }
}
}
}
You need to instantiate a new Automobile each time you iterate the while loop, otherwise you're just operating on the same instance and overwriting it.
Move this line:
Automobile car = new Automobile();
To here:
while (answer == "Y" || answer == "y")
{
Automobile car = new Automobile(); // create a new Automobile each time
Console.Write("\nEnter the make of the car: ");
car.Make = Console.ReadLine();
it may seem like the Automobile object within the list is getting overridden but you're actually adding the same object more than once and just overwriting it's attributes each time.
you'll need to insert this line Automobile car = new Automobile(); within the while loop in order to make a new object independent of the previous Automobile object.
while (answer == "Y" || answer == "y")
{
Automobile car = new Automobile();
...
...
...
whenever i run the program and select 7 it asks how many would you like which is really confusing, also I'm not sure if I'm adding the total items correctly. any help will be greatly appreciated.
namespace GoingShopping
{
class Program
{
private static int cabbageamount;
private static int tomatoamount;
private static int cheeseamount;
private static int breadamount;
private static int milkamount;
private static int onionamount;
bool isvalid = true;
static void Main(string[] args)
{
String cabbage = "1";
String tomatos = "2";
String Cheese = "3";
String bread = "4";
String milk = "5";
String onion = "6";
String done = "7";
String menu = "1) Cabbage" + System.Environment.NewLine +
"2) Tomatos" + System.Environment.NewLine +
"3) Cheese" + System.Environment.NewLine +
"4) Bread" + System.Environment.NewLine +
"5) Milk" + System.Environment.NewLine +
"6) Onion" + System.Environment.NewLine +
"7) I'm done shopping";
int total = cabbageamount + tomatoamount + cheeseamount + breadamount + milkamount + onionamount;
Console.Write("What you like to purchase ? " + System.Environment.NewLine);
Console.WriteLine(menu);
string wishlist = Console.ReadLine();
while (wishlist != "7")
{
switch (wishlist)
{
case "1":
Console.WriteLine("How many would you like ? ");
string cabbageinput = Console.ReadLine();
//int cabbageinput = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(menu);
break;
case "2":
Console.WriteLine("How many would you like ? ");
string tomatoinput = Console.ReadLine();
Console.WriteLine(menu);
break;
case "3":
Console.WriteLine("How many would you like ? ");
string cheeseinput = Console.ReadLine();
Console.WriteLine(menu);
break;
case "4":
Console.WriteLine("How many would you like ? ");
string breadinput = Console.ReadLine();
Console.WriteLine(menu);
break;
case "5":
Console.WriteLine("How many would you like ? ");
string milkinput = Console.ReadLine();
Console.WriteLine(menu);
break;
case "6":
Console.WriteLine("How many would you like ? ");
string onioninput = Console.ReadLine();
Console.WriteLine(menu);
break;
case "7":
Console.WriteLine("You have chosen to buy : " + System.Environment.NewLine);
Console.WriteLine(cabbageamount + "X" + "Cabbages" + System.Environment.NewLine,
tomatoamount + "X" + "Tomatos" + System.Environment.NewLine,
cheeseamount + "X" + "Cheese" + System.Environment.NewLine,
breadamount + "X" + "Bread" + System.Environment.NewLine,
milkamount + "X" + "Milk" + System.Environment.NewLine,
onionamount + "X" + "Onions" + System.Environment.NewLine);
Console.WriteLine("Giving a total of" + total + "items");
break;
default:
break;
}
Console.ReadLine();
}
}
}
}
As Daniel above said you need to set the wishlist variable again
so instead of
Console.ReadLine();
put
wishlist = Console.ReadLine();
at the end of the while loop.
You never set wishlist again, your last "Console.ReadLine()" throws away the result, so wishlist is always the same value.
However, as #Steve points out, you'd be better off taking a different approach completely.
As a general hint, you should use the debugger to "watch" what the values are as the program executes - then you'd notice that wishlist is the same value.
You need to set wishlist to the value you have read. Also, you need to do that before your switch:
namespace GoingShopping
{
class Program
{
private static int cabbageamount;
private static int tomatoamount;
private static int cheeseamount;
private static int breadamount;
private static int milkamount;
private static int onionamount;
bool isvalid = true;
static void Main(string[] args)
{
String cabbage = "1";
String tomatos = "2";
String Cheese = "3";
String bread = "4";
String milk = "5";
String onion = "6";
String done = "7";
String menu = "1) Cabbage" + System.Environment.NewLine +
"2) Tomatos" + System.Environment.NewLine +
"3) Cheese" + System.Environment.NewLine +
"4) Bread" + System.Environment.NewLine +
"5) Milk" + System.Environment.NewLine +
"6) Onion" + System.Environment.NewLine +
"7) I'm done shopping";
int total = cabbageamount + tomatoamount + cheeseamount + breadamount + milkamount + onionamount;
Console.Write("What you like to purchase ? " + System.Environment.NewLine);
Console.WriteLine(menu);
string wishlist = "0";
while (wishlist != "7")
{
wishlist = Console.ReadLine().Trim();
switch (wishlist)
{
case "1":
Console.WriteLine("How many would you like ? ");
string cabbageinput = Console.ReadLine();
//int cabbageinput = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(menu);
break;
case "2":
Console.WriteLine("How many would you like ? ");
string tomatoinput = Console.ReadLine();
Console.WriteLine(menu);
break;
case "3":
Console.WriteLine("How many would you like ? ");
string cheeseinput = Console.ReadLine();
Console.WriteLine(menu);
break;
case "4":
Console.WriteLine("How many would you like ? ");
string breadinput = Console.ReadLine();
Console.WriteLine(menu);
break;
case "5":
Console.WriteLine("How many would you like ? ");
string milkinput = Console.ReadLine();
Console.WriteLine(menu);
break;
case "6":
Console.WriteLine("How many would you like ? ");
string onioninput = Console.ReadLine();
Console.WriteLine(menu);
break;
case "7":
Console.WriteLine("You have chosen to buy : " + System.Environment.NewLine);
Console.WriteLine(cabbageamount + "X" + "Cabbages" + System.Environment.NewLine,
tomatoamount + "X" + "Tomatos" + System.Environment.NewLine,
cheeseamount + "X" + "Cheese" + System.Environment.NewLine,
breadamount + "X" + "Bread" + System.Environment.NewLine,
milkamount + "X" + "Milk" + System.Environment.NewLine,
onionamount + "X" + "Onions" + System.Environment.NewLine);
Console.WriteLine("Giving a total of" + total + "items");
break;
default:
break;
}
}
}
}
}
Your whole logic for the switch statement is wrong. You should not use string inside your switch statements. I would suggest you to change these into char :
char charcabbage = '1'; // or 0x31
char tomatos = '2'; // or 0x32
char Cheese = '3'; // or 0x33
char bread = '4'; // or 0x34
char milk = '5'; // or 0x35
char onion = '6'; // or 0x36
char done = '7'; // or 0x37
Then you should make some InputHandler to handle user input and then return your "action" :
char ChooseAction(string message)
{
Console.WriteLine(message);
string input = string.Empty;
while ( (input = Console.ReadLine()) != "exit")
{
char c = input.Trim()[0];
if ( c >= 0x31 && c <= 0x37)
return c;
Console.WriteLine("Wrong input. Try again...");
}
return 0x38;
}
Now this method awaits for "exit" if you would like to close it or something or for valid input "1"-"7".
And as you can see now user can input values from 0x31 to 0x37 and in your switch statement you're running the same code 6 times so ... optimize this in a bit and change
//private static int cabbageamount;
//private static int tomatoamount;
//private static int cheeseamount;
//private static int breadamount;
//private static int milkamount;
//private static int onionamount;
// to this :
private static System.Collections.Generic.Dictionary<char, int> _items;
And initialize this before your loop begins :
_items = new System.Collections.Generic.Dictionary<char, int>();
for(char i = '0'; i < '7'; i++) {
_items.Add(i, 0);
}
Proceeding to your "pre-loop" statements now you can do somehing like :
char action = ChooseAction("What you like to purchase ? " + System.Environment.NewLine + menu);
And then proceed with your while loop :
while (action >= 0x31 && action <= 0x37)
Then just insert your switch statement in this format :
case '7':
{
Console.WriteLine("You have chosen to buy : " + System.Environment.NewLine);
Console.WriteLine(_items[0x31] + "X" + "Cabbages" + System.Environment.NewLine,
_items[0x32] + "X" + "Tomatos" + System.Environment.NewLine,
_items[0x33] + "X" + "Cheese" + System.Environment.NewLine,
_items[0x34] + "X" + "Bread" + System.Environment.NewLine,
_items[0x35] + "X" + "Milk" + System.Environment.NewLine,
_items[0x36] + "X" + "Onions" + System.Environment.NewLine);
Console.WriteLine("Giving a total of" + total + "items");
// set list to completed:
action = 0x38;
}
break;
default :
{
Console.WriteLine("How many would you like ? ");
string input = Console.ReadLine();
int temp = 0;
if(int.TryParse(input, out temp)) {
_items[action] += temp;
}
action = ChooseAction(menu);
}
Now all your problems should be gone :)