C# - loop makes my app not work propely - c#

I have this app that I'm writing in C# just for practice purposes, this is the code,
using System;
namespace Stock_Control
{
class Program
{
static void Main(string[] args)
{
int qty, index;
string name, location, code;
Item item = new Item();
ConsoleKeyInfo opt;
do
{
Console.Clear();
Console.WriteLine();
Console.WriteLine("******************** STOCK CONTROL SOFTWARE *********************");
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Chose a option:");
Console.WriteLine("1 - Add item.");
Console.WriteLine("2 - View Stock.");
Console.WriteLine("3 - Remove item.");
Console.WriteLine("4 - Press 'Escape' to exit.");
opt = Console.ReadKey(true);
switch (opt.KeyChar.ToString())
{
case "1":
Console.WriteLine();
Console.Write("Enter the item code:");
code = Console.ReadLine();
Console.Write("Enter the item quantity:");
qty = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the item name:");
name = Console.ReadLine();
Console.Write("Enter the item location:");
location = Console.ReadLine();
item.add(code, qty, name, location);
break;
case "2":
Console.WriteLine("teste");
//item.view();
break;
case "3":
Console.WriteLine();
Console.WriteLine("Enter the index of the item to be removed:");
index = Int32.Parse(Console.ReadLine());
item.remove(index);
break;
}
} while (opt.Key != ConsoleKey.Escape);
}
}
}
It works fine but for some reason, when i wrapped around a loop, the second case in the switch statement stop working, once i remove the loop everything works fine. I can't figured out whats wrong.
Can someone help me with that?
Thanks.

It works still just fine but when you added the loop you do your Console.WriteLine("teste"); item.view(); in case "2" and then immediately start again = clear the console so you do not see anything.

Related

Is there a way that I can make my code return back to my UserChoice menu in C#?

I am currently new to C#, so I am not too familiar with some of the commands, methods, and syntax. I am currently making a medical program where I am asking the user to input their horse data, and vaccinations records and with the vaccination records I made it loop so if the user has more than one vaccination record they can add it and if the user does not have any more data to input they can type 0 but there is a problem with the it, when the user types 0 it does not return back to the main menu instead it still asks the user to still input vaccination record instead of breaking the loop. Also, it does not store the records; it's like everything defaults back to zero or none. Please can someone help me and walk me through it too so when I encounter something like this again in the future, I will be able to refer to it. Thank you so much for your help 🙂
Here is my code
switch (UserChoice)
{
case 1:
Console.WriteLine("Enter New Horse");
myHorse = AddHorse();
myHorse.PrintHorseInfo();
HorseList.Add(myHorse);
break;
case 2:
Console.WriteLine("Delete Horse");
Console.WriteLine("What Horse do you want to delete");
string aResponse = Console.ReadLine();
Console.WriteLine("Are you sure you want to delete");
string Response = Console.ReadLine();
if (Response.ToUpper() == "YES")
{
Console.WriteLine("You are now entering the deletion zone");
int i = HorseList.IndexOf(myHorse);
HorseList.RemoveAt(i);
{
Console.WriteLine($"{myHorse.Name} has been deleted");
}
}
else
{
Console.WriteLine("returning to the main menu");
}
break;
case 3:
Console.WriteLine("View all horses");
foreach (Horse h in HorseList)
{
h.PrintHorseInfo();
}
break;
case 4:
Console.WriteLine("Quit");
Environment.Exit(0);
break;
default:
Console.WriteLine("Choose an option to start");
break;
}
static Horse AddHorse()
{
Horse myHorse = new Horse();
Horse newHorse = null;
Console.WriteLine("Please enter your horse's common name");
String pName = Console.ReadLine();
Console.WriteLine("Please enter your horse's registered name");
String regName = Console.ReadLine();
Console.WriteLine("Please enter your horses breed");
String pBreed = Console.ReadLine();
Console.WriteLine("What year was your horse born?");
String pAge = Console.ReadLine();
int YearOfBirth;
Console.WriteLine("What is the size of your horse?");
String pSize = Console.ReadLine();
Console.WriteLine("Input your horse's vaccination record or enter 0 to exit.");
String iD = Console.ReadLine();
while (iD.Equals("0"))
{
Console.WriteLine("Input Vaccination Date");
String vacDate = Console.ReadLine();
Console.WriteLine("Input your horse's vaccination record or enter 0 to exit.");
iD = Console.ReadLine();
if (iD == "0")
{
break;
}
}
Here is my part of my Horse Class for the vaccinations records
Hashtable vaccination_records = new Hashtable();
public string getVacs()
{
String vacString = "Vac Records";
foreach (DictionaryEntry Vac in vaccination_records)
{
vacString = vacString + " " + Vac.Key + "-" + Vac.Value + "\n";
}
return vacString;
}
public void AddVac(string VacId, string LastDateVac)
{
vaccination_records.Add(VacId, LastDateVac);
}
Output:
With my first attempt I tried to see if I can use Enviroment.exit() method and I saw that it exited the entire program so I went back to the cutting board and tried to see if a break might work but that did not work so I tried to see if an If statement might be the one but I did not know how to set to make it do what I wanted it to do. Like I did not know what to type inside of my if statement :/
Ok you have several problems.
First of all if you want to entirely skip Vaccination block then you shoud to check that user input NOT equals to zero because the loop will be executed as long as the loop condition is true.
while (iD != "0")
Also you should save vaccinations records to myHorse object each time inside the loop before you exit the loop with break statement:
String vacDate = Console.ReadLine();
newHorse.AddVac(iD, vacDate);
Finally you store all parameters in the separated variables. But you never add them to the myHorse object. Your final code might look something like this:
static Horse AddHorse()
{
Horse myHorse = new Horse();
Console.WriteLine("Please enter your horse's common name");
myHorse.Name = Console.ReadLine();
Console.WriteLine("Please enter your horse's registered name");
myHorse.RegName = Console.ReadLine();
Console.WriteLine("Please enter your horses breed");
myHorse.Breed = Console.ReadLine();
Console.WriteLine("What year was your horse born?");
myHorse.Age = Console.ReadLine();
Console.WriteLine("What is the size of your horse?");
myHorse.Size = Console.ReadLine();
Console.WriteLine("Input your horse's vaccination record or enter 0 to exit.");
String iD = Console.ReadLine();
while (iD != "0")
{
Console.WriteLine("Input Vaccination Date");
String vacDate = Console.ReadLine();
myHorse.AddVac(iD, vacDate);
Console.WriteLine("Input your horse's vaccination record or enter 0 to exit.");
iD = Console.ReadLine();
// you don't need to check iD here
// because it will already be checked in the loop condition
}
return myHorse;
}

How to go back from a switch? c#

After I've added credits I want it to go back to display the main menu again. What is the way to do this? And is there an easier way? I am not very experienced in programming.
Console.WriteLine("-------------------------------");
Console.WriteLine("");
Console.WriteLine(" VENDING MACHINIES LTD");
Console.WriteLine("");
Console.WriteLine("-------------------------------");
Console.WriteLine(" Main Menu");
Console.WriteLine("");
Console.WriteLine("1 - Add Credits (current credits= 0.00)");
Console.WriteLine("2 - Select product/s");
Console.WriteLine("3 - Exit");
Cons
Try this code:
var returnBack = true;
do
{
Console.WriteLine("-------------------------------");
Console.WriteLine("");
Console.WriteLine(" VENDING MACHINIES LTD");
Console.WriteLine("");
Console.WriteLine("-------------------------------");
Console.WriteLine(" Main Menu");
Console.WriteLine("");
Console.WriteLine("1 - Add Credits (current credits= 0.00)");
Console.WriteLine("2 - Select product/s");
Console.WriteLine("3 - Exit");
Console.WriteLine("");
Console.Write("Please Enter A Number: ");
choice = Convert.ToInt32(Console.ReadLine());
while (choice < 1 || choice > 3)
{
Console.Write("Incorrect option. Please Re-Enter: ");
choice = Convert.ToInt32(Console.ReadLine());
}
switch (choice)
{
case 1:
Console.Write("How Many Credits Would You Like To Add? ");
credits = Convert.ToInt32(Console.ReadLine());
Console.Write("You Now Have {0} Credits", credits);
Console.WriteLine("");
Console.Write("Press return to go back to the main menu");
Console.ReadLine();
break;
case 2:
Console.WriteLine();
break;
case 3:
returnBack=false;
break;
}
} while (returnBack);
You can use while(true) for eternity cycle of menu and return for exit from your application
Console.WriteLine("-------------------------------");
Console.WriteLine("");
Console.WriteLine(" VENDING MACHINIES LTD");
Console.WriteLine("");
Console.WriteLine("-------------------------------");
while(true)
{
Console.WriteLine(" Main Menu");
Console.WriteLine("");
Console.WriteLine("1 - Add Credits (current credits= 0.00)");
Console.WriteLine("2 - Select product/s");
Console.WriteLine("3 - Exit");
Console.WriteLine("");
Console.Write("Please Enter A Number: ");
choice = Convert.ToInt32(Console.ReadLine());
while (choice < 1 || choice > 3)
{
Console.Write("Incorrect option. Please Re-Enter: ");
choice = Convert.ToInt32(Console.ReadLine());
}
switch (choice)
{
case 1:
Console.Write("How Many Credits Would You Like To Add? ");
credits = Convert.ToInt32(Console.ReadLine());
Console.Write("You Now Have {0} Credits", credits);
Console.WriteLine("");
Console.Write("Press return to go back to the main menu");
Console.ReadLine();
break;
case 2:
Console.WriteLine();
break;
case 3:
Console.WriteLine("Bye-bye");
return;
}
}
You can use a recursive method and I would also suggest to extract the "menu" console write lines. Please have a look on the following:
static void Main(string[] args)
{
DisplayMenu();
var choice = Convert.ToInt32(Console.ReadLine());
// Final response
choice = DisplayMenu(choice);
}
public static void DisplayMenu()
{
Console.WriteLine(" Main Menu");
Console.WriteLine("");
Console.WriteLine("1 - Add Credits (current credits= 0.00)");
Console.WriteLine("2 - Select product/s");
Console.WriteLine("3 - Exit");
Console.WriteLine("");
Console.Write("Please Enter A Number: ");
}
// Recursive overload
public static int DisplayMenu(int choice)
{
// If invalid input
if (choice<1 || choice>3)
{
Console.Write("Incorrect option. Please Re-Enter: ");
Console.WriteLine();
DisplayMenu();
return DisplayMenu(Convert.ToInt32(Console.ReadLine()));
}
// If valid show one more time the menu
DisplayMenu();
return Convert.ToInt32(Console.ReadLine());
}

Not enter in a switch case in C#

I can't enter in the case 2 of the switch statement and I don't know why. If I remove the do while loop the code runs perfectly. It's about something with the memory of the structure array? Here is the code:
class Notebook {
struct Student
{
public String id;
public String name;
public void showInfo(Student x) {
Console.WriteLine("\t ID: " + x.id);
Console.WriteLine("\t Name: " + x.name);
}
}
static void Main(string[] args){
bool display = true;
int studentNum = int.Parse(Console.ReadLine());
Student[] students = new Student[studentNum];
do {
Console.Clear();
Console.WriteLine("1.- Insert register");
Console.WriteLine("2.- Show register");
Console.WriteLine("3.- Exit");
String opc = Console.ReadLine();
switch (opc) {
case "1":
Console.Clear();
for(int i = 0; i < students.Length; ++i){
Console.WriteLine("Name of the student " + (i+1));
students[i].name = Console.ReadLine();
Console.WriteLine("ID of the student " + (i+1));
students[i].id = Console.ReadLine();
}
break;
case "2":
Console.Clear();
for(int i = 0; i < students.Length; ++i){
students[i].showInfo(students[i]);
}
break;
case "3":
Console.Clear();
Console.WriteLine("bye");
display = false;
break;
}
}while(display);
}
}
I think that is "something" in the memory of opc string that avoids the case 2.
Your problem is the Console.Clear statement that you run at start of do while loop. Comment that line and you will see that your code is going to case "2".
Its going to case "2" even in your original code, but console is every time being cleared at start of do while loop and so you don't see the statements written by case "2" logic.
There is no memory problem as you suspected.
The do while loop should have Console.Clear commented as in code below.
do {
//Console.Clear();
Console.WriteLine("1.- Insert register");
Console.WriteLine("2.- Show register");
Console.WriteLine("3.- Exit");
add a Console.ReadLine(); before break case "2".
case "2":
Console.Clear();
for (int i = 0; i < students.Length; ++i)
{
students[i].showInfo(students[i]);
}
Console.ReadLine();
break;
You write students informations and Call Console.Clear() after that

Return to a specific block of code in my application

I am fairly new to C# and currently building a simple ATM app. I am attempting to write code to return the user to the main menu according to his/her entry of the letter M. The break, continue, goto or return keywords do not seem to work in my scenario; perhaps I used them incorrectly. The statement directly below is where I would like to jump to.
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving");
I would like to jump from the line JUMP (below) within the else if statement nested within the switch statement into the section of code above. How can I achieve this? any help is appreciated...thanks!
switch (response)
{
case "C1":
Console.WriteLine("How much would you like to deposit to your checking account?");
string depositEntry = Console.ReadLine();
double checkingBalance = Convert.ToInt32(depositEntry) + currentCheckingBalance;
currentCheckingBalance += checkingBalance;
Console.WriteLine("Your current checking balance is " + checkingBalance + "\n (X) Exit, (M) Main Menu" );
string selection = Console.ReadLine().ToUpper();
if (selection == "X")
{
return;
}
else if (selection == "M")
{
***JUMP***
}
else
{
Console.WriteLine("Your entry was invalid");
}
break;
case "C2":
break;
case "W1":
Using a jump statement usually indicates the flow of logic is jumbled. I try to avoid any kind of jumps if necessary. The code below prints out a main menu and if the user types “x” the program will quit. If the user selects one of the other options, a message is simply printed out indicating what the user selected. After the user presses any key, the console clears and the main menu is re-displayed.
In the main menu, if the user does not type one of the selections, then the selection is ignored, the console is cleared, and the menu is reprinted. No error is displayed indicating invalid selections.
This does not require the user to type “m” to go back to the main menu. After a selection is made for Deposit/withdraw/… after the method is finished the code will automatically return to the main menu.
I am guessing this may be what you are looking for. Hope this helps.
static void Main(string[] args) {
string userInput = "";
while ((userInput = GetMainSelection()) != "x") {
switch (userInput) {
case "c1":
Console.WriteLine("C1 Deposit Checking method");
break;
case "c2":
Console.WriteLine("C2 Deposit Savings method");
break;
case "b1":
Console.WriteLine("B1 View Balance Checking method");
break;
case "b2":
Console.WriteLine("B2 View Balance Savings method");
break;
case "w1":
Console.WriteLine("W1 Withdraw Checking method");
break;
case "w2":
Console.WriteLine("W2 withdraw Savings method");
break;
}
Console.WriteLine("Press Any Key to continue"); // <-- show what method was just used
Console.ReadKey();
Console.Clear();
}
Console.Write("Press any key to exit the program");
Console.ReadKey();
}
private static string GetMainSelection() {
string userInput = "";
while (true) {
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving. (X) to EXit");
userInput = Console.ReadLine().ToLower();
if (userInput == "b1" || userInput == "b2" || userInput == "c1" || userInput == "c2" || userInput == "w1" || userInput == "w2" || userInput == "x") {
return userInput;
}
else {
Console.Clear();
}
}
}
Put the JUMP code in a function and return.
public void MainMenu() {
// Show the main menu
}
public void Response(string response) {
switch (response)
{
case "C1":
Console.WriteLine("How much would you like to deposit to your checking account?");
string depositEntry = Console.ReadLine();
double checkingBalance = Convert.ToInt32(depositEntry) + currentCheckingBalance;
currentCheckingBalance += checkingBalance;
Console.WriteLine("Your current checking balance is " + checkingBalance + "\n (X) Exit, (M) Main Menu" );
string selection = Console.ReadLine().ToUpper();
if (selection == "X")
{
return;
}
else if (selection == "M")
{
***JUMP***
MainMenu();
return;
}
else
{
Console.WriteLine("Your entry was invalid");
}
break;
case "C2":
break;
case "W1":
}
}
Similar to the already given answer, I suggest breaking this out. Here's an example:
The Main method:
static void Main(string[] args) {
string input = null;
do {
input = Console.ReadLine();
ParseInput(input);
} while (input != "X");
}
ParseInput:
static void ParseInput(string input) {
switch (input) {
case "X": //from Main(), this will close the app
return;
case "M":
MainMenu();
break;
case "C1":
ShowAccount("C1"); //move your deposit/withdraw logic into a method and call with the selected account
return;
//other accounts
default:
break; //error message?
}
}
and MainMenu:
static void MainMenu() {
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving");
}
This should let you read the input in a loop and the ParseInput function can handle your individual cases. You may also want to call MainMenu() at the start, so it shows from the beginning.
It works like this:
Get input from the user
Pass the input to ParseInput() which decides where to go next.
Any functions hit in ParseInput() will execute, writing to the console or asking for further input
Once that function returns, while (input != "X") evaluates. If input != "X", goto 1, else exit.
I suggest you use goto C# reference.
static void Main()
{
int x = 200, y = 4;
int count = 0;
string[,] array = new string[x, y];
// Initialize the array:
for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++)
array[i, j] = (++count).ToString();
// Read input:
Console.Write("Enter the number to search for: ");
// Input a string:
string myNumber = Console.ReadLine();
// Search:
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
if (array[i, j].Equals(myNumber))
{
goto Found;
}
}
}
Console.WriteLine("The number {0} was not found.", myNumber);
goto Finish;
Found:
Console.WriteLine("The number {0} is found.", myNumber);
Finish:
Console.WriteLine("End of search.");
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
Output for the Input 44 would be:
Enter the number to search for: 44
The number 44 is found.
End of search.
See here for the MSDN reference.

A simple menu in a Console Application

I am trying to get my menu to repeat, so after selecting and doing option 1, it will got back to the menu and ask for another option to be chosen
class Program
{
static void Main(string[] args)
{
FootballTeams MyCode = new FootballTeams();
MyCode.ListInit();
MyCode.DisplayMenu();
MyCode.AddTeams();
Console.ReadLine();
MyCode.ListInit();
MyCode.DisplayMenu();
MyCode.DisplayTeams();
Console.ReadLine();
MyCode.ListInit();
MyCode.DisplayMenu();
MyCode.Delete();
Console.ReadLine();
MyCode.ListInit();
MyCode.DisplayMenu();
MyCode.TeamSearch();
Console.ReadLine();
}
}
Here are the methods with the contents taken out:
class FootballTeams
{
public FootballTeams(){ }
List<string> teams;
public void ListInit()
public void DisplayMenu()
{
Console.WriteLine("Football Manager");
Console.WriteLine();
Console.WriteLine("1. Add a Football team");
Console.WriteLine("2. List the Football teams");
Console.WriteLine("3. Search for a Football team");
Console.WriteLine("4. Delete a team");
Console.ReadLine();
}
public void AddTeams()
{
Console.WriteLine("Enter a team to be added: ");
string userinput = Console.ReadLine();
if (teams.Count < 10)
{
if (userinput != "Colchester")
{
teams.Add(userinput);
foreach (var item in teams)
Console.Write(item.ToString() + " ");
}
else
Console.Write("NOT ALLOWED");
}
else
Console.Write("MAXIMUM LIMIT REACHED");
}
public void DisplayTeams()
{
foreach(var item in teams)
Console.Write(item.ToString() + " ");
}
public void TeamSearch()
{
Console.WriteLine("Please enter the team you wish to search for: ");
string userinput = Console.ReadLine();
if (teams.Contains(userinput))
Console.WriteLine("Success, team " + userinput);
}
public void Delete()
{
Console.WriteLine("Enter a team you wish to delete: ");
string userinput = Console.ReadLine();
teams.Remove(userinput);
foreach (var item in teams)
Console.Write(item.ToString() + " ");
}
I know I have worded this poorly, so I hope that someone understands what I'm asking :P
You can use a do while loop for the purpose
Make a little modification to your DispalyMenu() method and return the result like this
static public int DisplayMenu()
{
Console.WriteLine("Football Manager");
Console.WriteLine();
Console.WriteLine("1. Add a Football team");
Console.WriteLine("2. List the Football teams");
Console.WriteLine("3. Search for a Football team");
Console.WriteLine("4. Delete a team");
Console.WriteLine("5. Exit");
var result = Console.ReadLine();
return Convert.ToInt32(result);
}
and write this in your Main() method
int userInput = 0;
do
{
userInput = DisplayMenu();
}while(userInput!=5);
So for the time being the user does not enter '5', the code will execute in the loop.
Hope that helps.
See Console.ReadKey().
Replace your main function with:
static void Main(string[] args) {
FootballTeams MyCode = new FootballTeams();
MyCode.ListInit();
ConsoleKeyInfo cki;
do {
MyCode.DisplayMenu();
cki = Console.ReadKey(false); // show the key as you read it
switch (cki.KeyChar.ToString()) {
case "1":
MyCode.AddTeams();
break;
case "2":
MyCode.DisplayTeams();
break;
// etc..
}
} while (cki.Key != ConsoleKey.Escape);
}
Essentially, you need to loop until they press the Escape key. Each time you read the key, you can execute the action selected.
There is a nuget package for this now
https://github.com/splttingatms/EasyConsole
Example
After adding the nuget package the Menu can be implemented the following way, This is a very Basic option
static void Main(string[] args)
{
var menu = new EasyConsole.Menu()
.Add("foo", () => Console.WriteLine("foo selected"))
.Add("bar", () => Console.WriteLine("bar selected"));
menu.Display();
}
In the action you can place Any Method to run when selected
This will output something like this
foo
bar
Choose an option:

Categories