C# Make a grocery list with a Switch Statement - c#

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 :)

Related

Choosing in menu wirh arrows on keyboard (C#)

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:

Do loop is looping when I don't want it to in my 'game choices' program

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".

How to start over with my code? C# Console [duplicate]

This question already has answers here:
How to loop a Console App
(6 answers)
Closed 6 years ago.
I wanted to try how the if conditional works so I created this code almost by myself. I also had problems with random into int.
Here's my code:
using System;
namespace Bigger_Smaller_Equal
{
class Program
{
static void Main(string[] args)
{
int min = 1;
int max = 100;
Random rnd = new Random();
int gen = rnd.Next(min, max);
Console.WriteLine("My Number is : " + gen + "!");
Console.WriteLine("Tell me your number:");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num == gen)
{
Console.WriteLine(num + " is Equal to " + gen);
}
else if (num > gen)
{
Console.WriteLine(num + " Is Bigger than " + gen);
}
else if (num < gen)
{
Console.WriteLine(num + " Is Smaller than " + gen);
}
Console.WriteLine("Press Any Key to exit.");
Console.ReadLine();
}
}
}
How to make the console stop, so it will allow me to enter another number?
Basically:
I write a number it tells me if its smaller bigger or equal to number which was randomly generated
After I press enter instead of closing the console the number will be generated again and I can write new number and so on.
Here's an example using goto, although it is not recommended for more complex applications as you could end up creating endless loops. Feel free to try it out
static void Main(string[] args)
{
int min = 1;
int max = 100;
Random rnd = new Random();
again:
int gen = rnd.Next(min, max);
Console.WriteLine("My Number is : " + gen + "!");
Console.WriteLine("Tell me your number:");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num == gen)
{
Console.WriteLine(num + " is Equal to " + gen);
}
else if (num > gen)
{
Console.WriteLine(num + " Is Bigger than " + gen);
}
else if (num < gen)
{
Console.WriteLine(num + " Is Smaller than " + gen);
}
repeat:
Console.WriteLine("Play again? (Y/N)");
string ans = Console.ReadLine();
switch (ans.ToUpper())
{
case "Y": goto again; break;
case "N": break; //continue
default: goto repeat; break;
}
}
You can use console.ReadKey() insted of using console.ReadLine().
console.ReadLine() wait for input set of character thats why you console window is apperre there after pressing any key.
You can use "do while" or "while" operator.If you dont want to use while(true) , you can use this diffirent way. I mean that when user enter 0 or -1 this system can stop. while()
bool repeat = true;
do
{
Console.WriteLine("Enter value ");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num!=0)
// bla bla bla.
else
repeat = false;
}while (repeat);

C# Can´t just get to add values to 2D matrix from console

Need help with this program. It´s almost done, but still have some issues to solve. This is the complete code
object[,] data = new object[5, 5];
//Adding values to matrix
public void load()
{
for (int i = 0; i <= 4; i++)
{
for (int j = 0; j <= 4; j++)
{
string[] input = Console.ReadLine().Split('=');
string[] coordinates = input[0].Split(',');
int[] intCoordinates = coordinates.Select(s => int.Parse(s)).ToArray();
data[intCoordinates[0], intCoordinates[1]] = int.Parse(input[1]);
}
}
}
//Viewing matrix created
public void view()
{
Console.WriteLine("\n" + "\n" + "Matrix created is:");
for (int i = 0; i <= 4; i++)
{
Console.Write("\n");
for (int j = 0; j <= 4; j++)
{
Console.Write(data[i, j].ToString());
}
}
Console.ReadKey();
}
static void Main(string[] args)
{
Program objeto = new Program();
char letter;
//Main menu
menu:
Console.WriteLine("\t" + "\t" + "\t" + "\t" + "WELCOME" + "\n" + "\n" + "\n");
Console.Write("Select an option:" + "\n" + "\n");
Console.Write("\t" + "a) Add value to matrix" + "\n");
Console.Write("\t" + "b) View matrix" + "\n");
Console.Write("\t" + "c) End" + "\n");
letter = Console.ReadKey().KeyChar;
switch (letter)
{
case 'a':
{
add:
Console.Clear();
Console.WriteLine("Set value in:" + "\n" + "\n");
objeto.load();
Console.WriteLine("Do you want to add another value Y/N" + "\n" + "\n");
letter = Console.ReadKey().KeyChar;
switch (letter)
{
case 'y':
{
goto add;
}
case 'n':
{
Console.WriteLine("Returning to Main Menu");
Console.Clear();
goto menu;
}
default:
{
Console.WriteLine("Error, returning to Main Menu");
Console.Clear();
goto menu;
}
}
}
case 'b':
{
objeto.view();
Console.ReadKey();
Console.WriteLine("Returning to Main Menu");
Console.Clear();
goto menu;
}
case 'c':
{
goto end;
}
default:
{
Console.WriteLine("Error, try again");
Console.ReadKey();
Console.Clear();
goto menu;
}
}
//Ending menu
end:
Console.WriteLine("\n" + "\n" + "¿Exit program? S/N");
letter = Console.ReadKey().KeyChar;
switch (letter)
{
case 'n':
{
Console.ReadKey();
Console.Clear();
goto menu;
}
case 's':
{
break;
}
default:
{
Console.Write("\n" + "\n" + "Error, try again");
goto end;
}
}
Console.WriteLine("Closing, press any key");
Console.ReadKey();
So, the program is supposed to create a 5x5 matriz, and, then from console, the user should be able to add an * (only *, that´s why im using "object"), anywhere he wants to, let´s say for example row 2 column 4. The program should also let the user view the matrix with all the * added and navigate the program tru menus, which are working just fine.
I already posted parts of the program before, and have solved several problems, so this time we go for final "details". The program can be used, but then:
1.- Load code is not working correctly, while running i always get IndexOutOfRangeException when adding a number or FormatException when adding the *. So the code has a mistake or either i don´t know how to set the value in from console.
2.- View code throws NullReferenceException, but i think it´s becasuse the matrix is empty, but i always thought that when created and not assigned values, matrix values were 0´s by defalut.
3.- How can i get the user to use only * for the program?
Help´ll be greatly appreciated n_n

TimeSpan to Localized String in C#

Is there an easy way (maybe built in solution) to convert TimeSpan to localized string? For example new TimeSpan(3, 5, 0); would be converted to 3 hours, 5minutes (just in polish language).
I can of course create my own extension:
public static string ConvertToReadable(this TimeSpan timeSpan) {
int hours = timeSpan.Hours;
int minutes = timeSpan.Minutes;
int days = timeSpan.Days;
if (days > 0) {
return days + " dni " + hours + " godzin " + minutes + " minut";
} else {
return hours + " godzin " + minutes + " minut";
}
}
But this gets complicated if i want to have proper grammar involved.
The easiest way to do this is to put the format string in a localized resource, and translate appropriately for each supported language.
Unfortunately there's no standard way to do such thing.
Nobody seems to agree in what should be the proper way.... :-\
And people like us that write software for multiple languages suffer.
I do not think this is possible. What you can do is something like this:
public static string ConvertToReadable(this TimeSpan timeSpan) {
return string.Format("{0} {1} {2} {3} {4} {5}",
timeSpan.Days, (timeSpan.Days > 1 || timeSpan.Days == 0) ? "days" : "day",
timeSpan.Hours, (timeSpan.Hours > 1 || timeSpan.Hours == 0) ? "hours" : "hour",
timeSpan.Minutes, (timeSpan.Minutes > 1 || timeSpan.Minutes == 0) ? "minutes" : "minute");
}
Here's the code that I've cooked out:
public static string ConvertToReadable(this TimeSpan timeSpan) {
int hours = timeSpan.Hours;
int minutes = timeSpan.Minutes;
int days = timeSpan.Days;
string hoursType;
string minutesType;
string daysType;
switch (minutes) {
case 1:
minutesType = "minuta";
break;
case 2:
case 3:
case 4:
minutesType = "minuty";
break;
default:
minutesType = "minut";
break;
}
switch (hours) {
case 1:
hoursType = "godzina";
break;
case 2:
case 3:
case 4:
hoursType = "godziny";
break;
default:
hoursType = "godzin";
break;
}
switch (days) {
case 1:
daysType = "dzień";
break;
default:
daysType = "dni";
break;
}
if (days > 0) {
return days + " " + daysType + " " + hours + " " + hoursType + " " + minutes + " " + minutesType;
}
return hours + " " + hoursType + " " + minutes + " " + minutesType;
}

Categories