Switch och felhantering
Hej,
Jag behöver få in en switch samt en felhantering(try, catch) i min kod. Någon som har ett förslag hur jag kan skriva ut det utan att det blir error?
Använder replit som editor
using System;
class Program {
public static void method1(){
//method 1
Console.WriteLine("Godismaskinen är aktiverad!");
}
public static void PrintNumber(){
//method 2
Random numGen = new Random();
int name = numGen.Next(1,100);
Console.WriteLine("Totalsumman blir" + " " + name + "kr\n");
Console.WriteLine("Tack för din order!\n");
}
public static void Amount(){
//method 3
Random numGen = new Random();
int name1 = numGen.Next(1,999);
Console.WriteLine("Du har lagt till" + " " + name1 + " " + "godisar i varukorgen\n");
}
public static void Main (string[] args) {
Console.Clear();
//Starting program
Console.WriteLine("Startar upp program...");
method1();
String name = Console.ReadLine();
//Varible using to hold things
int x = 0;
while(true){
//Fixing, cleaning the menu
Console.Clear();
//Text to show the menu
Console.WriteLine("Välj det godis du är sugen på!");
Console.WriteLine("-----------------------------");
Console.WriteLine("1.Marabou");
Console.WriteLine("2.Ahlgrens bilar");
Console.WriteLine("3.Kexchoklad");
Console.WriteLine("4.Tuggummi bubbelgum");
Console.WriteLine("5.Räkna ut summan");
Console.WriteLine("6.Avsluta programmet\n");
//Getting users choice
Console.WriteLine("Skriv in ditt val");
x = Convert.ToInt32(Console.ReadLine());
//Conditions to get the function of choice
if (x == 1){
Console.Clear();
Amount();
Console.WriteLine("Tryck Enter för att gå tillbaka till menyn");
Console.ReadKey();
}
else if (x == 2){
Console.Clear();
Amount();
Console.WriteLine("Tryck Enter för att gå tillbaka till menyn");
Console.ReadKey();
}
else if (x == 3){
Console.Clear();
Amount();
Console.WriteLine("Tryck Enter för att gå tillbaka till menyn");
Console.ReadKey();
}
else if (x == 4){
Console.Clear();
Amount();
Console.WriteLine("---------------------------------");
Console.WriteLine("Tryck Enter för att gå tillbaka till menyn");
Console.ReadKey();
}
else if (x == 5){
Console.Clear();
PrintNumber();
Console.WriteLine("Tryck Enter för att gå tillbaka till menyn");
Console.ReadKey();
}
//To exit the program
else if (x == 6){
Console.Clear();
Console.WriteLine("Du har valt att avsluta programmet");
Console.WriteLine("Tryck enter för att avsluta programmet");
Console.ReadKey();
Console.Clear();
Console.WriteLine("Programmet har avslutats, välkommen åter!");
break;
}
//If user press number outside of choice
else{
Console.Clear();
Console.WriteLine("Du gjorde inget giltigt val!\nGå tillbaka till menyn och gör ett nytt val!");
Console.WriteLine("Tryck Enter för att gå tillbaka till menyn");
Console.ReadKey();
}
}
}
}