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();
...
...
...
Related
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:
Fixed, but now it automatically presses enter when it gets to the Main(); thing and I can't actually input anything in time. Anyone know what's wrong?
using System;
using System.Linq;
namespace Bruh
{
class Program
{
static void Main()
{
int pog = 0;
int pog2 = 0;
Random r = new Random();
Console.WriteLine("Input a whole number");
string poggers = Console.ReadLine();
if (int.TryParse(poggers, out pog))
{
pog = int.Parse(poggers);
}
else
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
Console.Read();
System.Environment.Exit(1);
}
Console.WriteLine("Input a number higher than the previous");
string poggers2 = Console.ReadLine();
if (int.TryParse(poggers2, out pog2))
{
pog2 = int.Parse(poggers2);
}
else
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
Console.Read();
System.Environment.Exit(1);
}
int genRand = r.Next(pog, pog2);
Console.WriteLine("This number was randomly generated between " + pog + " and " + pog2 + " and we got: " + genRand);
Console.Read();
Console.WriteLine("Would you like to try again? Y/N");
ConsoleKeyInfo answer = Console.ReadKey();
if (answer.KeyChar == 'y' || answer.KeyChar == 'Y')
{
Console.WriteLine("\n");
Main();
}
else if (answer.KeyChar == 'n' || answer.KeyChar == 'N')
{
System.Environment.Exit(1);
}
else
{
Console.WriteLine("ERROR: Y/N not any other character");
Console.Read();
System.Environment.Exit(1);
}
}
}
}
I've reworked your code into something that is more C#-like :-) - find this below.
Highlights:
You use int.TryParse() correctly, but do the conversion again
inside the true code block, using int.Parse().
No need to call System.Environment.Exit(1); to terminate the program, just let it end.
The call main() is actually a recursive call - where a method (function) calls it self. Usable sometimes, but i often leads to a StackOverflow exception. In this case, you get some strange behaviour...
using System;
namespace Bruh2
{
class Program
{
static void Main()
{
bool tryAgain = true;
while (tryAgain)
{
int pog = 0;
int pog2 = 0;
Random r = new Random();
Console.Write("Input a whole number: ");
string poggers = Console.ReadLine();
while (!int.TryParse(poggers, out pog))
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
poggers = Console.ReadLine();
}
Console.Write("Input a number higher than the previous: ");
string poggers2 = Console.ReadLine();
while (!int.TryParse(poggers2, out pog2))
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
poggers2 = Console.ReadLine();
}
int genRand = r.Next(pog, pog2);
Console.WriteLine("This number was randomly generated between " + pog + " and " + pog2 + " and we got: " + genRand);
Console.WriteLine();
Console.WriteLine("Would you like to try again? Y/N");
//ConsoleKeyInfo answer = Console.ReadKey();
string answer = Console.ReadKey().KeyChar.ToString().ToLower();
while (answer!="y" && answer!="n")
{
Console.WriteLine("ERROR: Y/N not any other character");
answer = Console.ReadKey().ToString().ToLower();
}
if (answer == "n")
{
tryAgain = false; // terminate the loop (and thereby the program)
}
}
}
}
}
I have an assesment where we have to implement methods in an app to store employees info in a 2D array and display it onscreen. So far the code works ok like this but I can't figure out a way to pass the 2D array information to the case 2 of the switch. It always results in an IndexOutOfRangeException when I try to return the array info from the UserInput method or when creating a method for case 2 and trying to pass the array. This is the code i have, thanks in advance for the help:
using System;
namespace EmployeeFileWithMethods
{
class Program
{
static void Main(string[] args)
{
int numberEmployees = 0;
string[,] table = new string[numberEmployees, 4];
string userInput = "1";
while ( userInput != "0" )
{
userInput = Intro();
switch ( userInput )
{
case "1":
UserInput();
break;
case "2":
Console.Clear();
for ( int user = 0; user < table.GetLength(0); user++ )
{
Console.WriteLine(" User " + ( user + 1 ));
for ( int row = 0; row < table.GetLength(1); row++ )
{
Console.Write(table[user, row] + "\n");
}
Console.WriteLine("");
}
break;
case "0":
break;
default:
{
DefaultCase();
break;
}
}
}
Console.WriteLine("Thanks for using the app!");
Console.ReadLine();
}
public static string Intro()
{
Console.WriteLine("[-------------------------------------------------------------------------------]");
Console.WriteLine(" Welcome to the Edinburgh College App \n What would you like to do?\n 1:Add User\n 2:Show User Info\n 0:Exit");
Console.WriteLine("[-------------------------------------------------------------------------------]");
string userInput = Console.ReadLine();
return userInput;
}
public static void DefaultCase()
{
Console.Clear();
Console.WriteLine("[-------------------------------------------------------------------------------]");
Console.WriteLine(" The option that you entered is invalid. Please try again. ");
Console.WriteLine("[-------------------------------------------------------------------------------]");
}
public static void UserInput()
{
Console.WriteLine("How many employees does your company have?");
int numberEmployees = Convert.ToInt32(Console.ReadLine());
string[,] table = new string[numberEmployees, 4];
for ( int row = 0; row < numberEmployees; row++ )
{
Console.WriteLine("Write the Forename of user " + ( row + 1 ));
string forename = Console.ReadLine();
table[row, 0] = forename;
Console.WriteLine("Write the Surname of user " + ( row + 1 ));
string surname = Console.ReadLine();
table[row, 1] = surname;
while ( true )
{
Console.WriteLine("Write the Phone of user " + ( row + 1 ));
string phone = Console.ReadLine();
if ( phone.Length == 11 )
{
table[row, 2] = phone;
break;
}
else
{
Console.WriteLine("Invalid Phone Number. Please Try Again");
continue;
}
}
while ( true )
{
Console.WriteLine("Write the Email of user " + ( row + 1 ));
string email = Console.ReadLine();
int charPos = email.IndexOf('#');
if ( charPos > 0 )
{
table[row, 3] = email;
break;
}
else
{
Console.WriteLine("Invalid Email. Please Try Again");
continue;
}
}
}
}
}
}
I can't reproduce the exception, but UserInput returns nothing and the table initialized in this method is lost at the return. So the table in Main has a size for the first dim of 0. You should pass the table as a parameter by ref and remove the table declaration in the method:
UserInput(table);
public static void UserInput(ref string[,] table)
But you need to resize this array to add new inputs.
A better and more simple and robust and cleaner way is to use a list of a class entity. Here is the code adapted and improved to use a list of an employee entity. I touched the code a minimum but it can be improved and refactored more, especially the while loops, and also you can use int.TryParse for the number of employees to add.
using System.Collections.Generic;
public class Employee
{
public string Forename { get; set; }
public string Surname { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
static private void Main()
{
var employees = new List<Employee>();
string userInput = "1";
while ( userInput != "0" )
{
userInput = Intro();
switch ( userInput )
{
case "1":
UserInput(employees);
break;
case "2":
Console.Clear();
for ( int index = 0; index < employees.Count; index++ )
{
Console.WriteLine(" User " + ( index + 1 ));
Console.WriteLine(" Forename: " + employees[index].Forename);
Console.WriteLine(" Surname: " + employees[index].Surname);
Console.WriteLine(" Phone: " + employees[index].Phone);
Console.WriteLine(" eMail: " + employees[index].Email);
Console.WriteLine("");
}
break;
case "0":
break;
default:
{
DefaultCase();
break;
}
}
}
Console.WriteLine("Thanks for using the app!");
Console.ReadLine();
}
public static void UserInput(List<Employee> employees)
{
Console.WriteLine("How many employees does your company have?");
int countEmployees = employees.Count;
int countEmployeesNew = Convert.ToInt32(Console.ReadLine());
for ( int indexEmployeeNew = 0; indexEmployeeNew < countEmployeesNew; indexEmployeeNew++ )
{
int posEmployeeNew = countEmployees + indexEmployeeNew + 1;
Console.WriteLine("Write the Forename of user " + posEmployeeNew);
string forename = Console.ReadLine();
Console.WriteLine("Write the Surname of user " + posEmployeeNew);
string surname = Console.ReadLine();
string phone = "";
while ( true )
{
Console.WriteLine("Write the Phone of user " + posEmployeeNew);
phone = Console.ReadLine();
if ( phone.Length == 11 ) break;
Console.WriteLine("Invalid Phone Number. Please Try Again");
}
string email = "";
while ( true )
{
Console.WriteLine("Write the Email of user " + posEmployeeNew);
email = Console.ReadLine();
int charPos = email.IndexOf('#');
if ( charPos > 0 ) break;
Console.WriteLine("Invalid Email. Please Try Again");
}
employees.Add(new Employee
{
Forename = forename,
Surname = surname,
Phone = phone,
Email = email
});
}
}
i am trying to give the user 2 options one is to see what the array stored, and the second option is to enter the new items. Any help please! I have tried to add the array in the method ItemInfo() but it doesn't work as well, i have tried to do like this in switch:
ItemInfo(itemNArr[itemN],itemNameArr[itemName],itemPriceArr[itemPrice],itemStockArr[itemNStock],itemRatingArr[itemRating]
but still does not work as well. So what i should do in this case to pass the user input to the array and store it!? I will appreciate the help.
The problem that i got is:
The name 'itemN' does not exist in the current context line 37
The name 'itemName' does not exist in the current context line 37
The name 'itemPrice' does not exist in the current context line 37
The name 'itemNStock' does not exist in the current context line 37
The name 'itemRating' does not exist in the current context line 37
And the code is here:
using System;
using System.Security.Cryptography.X509Certificates;
using static System.Console;
namespace program
{
class UseItem
{
public static void Main(string[] args)
{
int item = AppIntro();
string[] itemNArr = new string[item];
string[] itemNameArr = new string[item];
double[] itemPriceArr = new double[item];
int[] itemStockArr = new int[item];
int[] itemRateArr = new int[item];
// ask to enter price for produect
for (int i = 0; i < item; i++)
{
Clear();
ItemInfo(i, out itemNameArr[i], out itemPriceArr[i], itemStockArr[i], itemRateArr[i]);
Clear();
}
string ans;
do
{
WriteLine("What would you like to do next?");
WriteLine(" Enter 1 to display individual course" + " and 2 to add a new product");
int option = int.Parse(ReadLine());
int result = int.Parse(ReadLine());
switch (option)
{
case 1:
DisplayItems(itemNArr,itemNameArr,itemPriceArr, itemStockArr, itemRateArr);
break;
case 2:
result = ItemInfo(itemN, itemName,itemPrice,itemNStock,itemRating);
break;
default:
WriteLine("No valid entery was entered. " + "i decided to exit the application.... ");
break;
}
WriteLine("\n\nWould you like to do another operation?");
ans = ReadLine();
} while (ans == "Yes" || ans == "yes");
WriteLine("\n\nThank you for choosing our application.... coma back again :) ");
}
public static int AppIntro()
{
WriteLine("Welcome to the PSO App: ");
WriteLine("You will be asked to enter the product name" + " product price, how many you have in stock of the product" + " and the rate of the product");
WriteLine("Then you will have a choise to display individual product" + "info");
WriteLine("\n\nHow many products you want to add!?");
return int.Parse(ReadLine());
}
public static void ItemInfo(int itemN, out string itemName, out double itemPrice, int itemNStock, int itemRating)
{
Write(" Enter the item number {0}:", itemN+1);
itemName = ReadLine();
Write(" Enter the item name: ");
itemName = ReadLine();
Write(" Enter the item price: ");
itemPrice = double.Parse(ReadLine());
Write(" Enter the number of the item in stock: ");
itemNStock = int.Parse(ReadLine());
Write(" Enter the rate of the item: ");
itemRating = int.Parse(ReadLine());
}
public static void DisplayItems(string[]itemN, string[] itemName, double[] itemPrice, int[] itemNStock, int[] itemRating)
{
Write(" Which items would you like to display? Enter it's number: ");
string valueIn = ReadLine();
int n = 0;
for(int i=0; i < itemN.Length; i++)
{
if(valueIn == itemN[i])
{
n = i;
}
Clear();
WriteLine("Your item info: ");
WriteLine("item number is: " + itemN[n]);
WriteLine("item name is: " + itemName[n]);
WriteLine(" item price is: " + itemPrice[n]);
WriteLine(" number of item in the stock is: " + itemNStock[n]);
WriteLine(" item rate is: " + itemRating[n]);
}
}
}
}
I was close to the answer and finally i want to say that here is the answer of my questions.
using System;
using System.Security.Cryptography.X509Certificates;
using static System.Console;
namespace program
{
class UseItem
{
public static void Main(string[] args)
{
int n = 0;
int item = AppIntro();
string[] itemNArr = new string[item];
string[] itemNameArr = new string[item];
double[] itemPriceArr = new double[item];
int[] itemStockArr = new int[item];
int[] itemRateArr = new int[item];
// ask to enter price for produect
//for (int i = 0; i < item; i++)
//{
//Clear();
n = ItemInfo(n, itemNArr, itemNameArr, itemPriceArr, itemStockArr, itemRateArr);
//Clear();
//}
string ans;
do
{
// WriteLine("What would you like to do next?");
WriteLine(" Enter 1 to display individual course" + " and 2 to add a new product");
int option = int.Parse(ReadLine());
//int result = int.Parse(ReadLine());
switch (option)
{
case 1:
DisplayItems(itemNArr,itemNameArr,itemPriceArr, itemStockArr, itemRateArr);
break;
case 2:
n = ItemInfo(n, itemNArr, itemNameArr, itemPriceArr, itemStockArr, itemRateArr);
break;
default:
WriteLine("No valid entery was entered. " + "i decided to exit the application.... ");
break;
}
WriteLine("\n\nWould you like to do another operation?");
ans = ReadLine();
} while (ans == "Yes" || ans == "yes");
WriteLine("\n\nThank you for choosing our application.... come back again :) ");
}
public static int AppIntro()
{
WriteLine("Welcome to the PSO App: ");
WriteLine("You will be asked to enter the product name" + " product price, how many you have in stock of the product" + " and the rate of the product");
WriteLine("Then you will have a choise to display individual product" + "info");
WriteLine("\n\nHow many products you want to add!?");
return int.Parse(Console.ReadLine());
}
public static int ItemInfo(int n, string[] itemN, string[] itemName, double[] itemPrice, int[] itemNStock, int[] itemRating)
{
Write(" Enter the item number:");
itemN[n] = ReadLine();
Write(" Enter the item name: ");
itemName[n] = ReadLine();
Write(" Enter the item price: ");
itemPrice[n] = double.Parse(ReadLine());
Write(" Enter the number of the item in stock: ");
itemNStock[n] = int.Parse(ReadLine());
Write(" Enter the rate of the item: ");
itemRating[n] = int.Parse(ReadLine());
n++;
return n;
}
public static void DisplayItems(string[]itemN, string[] itemName, double[] itemPrice, int[] itemNStock, int[] itemRating)
{
Write(" Which items would you like to display? Enter it's number: ");
string valueIn = ReadLine();
int n = 0;
for(int i=0; i < itemN.Length; i++)
{
if(valueIn == itemN[i])
{
n = i;
}
Clear();
WriteLine("Your item info: ");
WriteLine("item number is: " + itemN[n]);
WriteLine("item name is: " + itemName[n]);
WriteLine(" item price is: " + itemPrice[n]);
WriteLine(" number of item in the stock is: " + itemNStock[n]);
WriteLine(" item rate is: " + itemRating[n]);
}
}
}
}
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".