'Trying to call on switch case in a class from program.cs
Iam creating a calculator and using switch case for the operators ( +,-,*,/ etc.) But the problem is that I dont know what exactly to type in the class. I have tried abstract and I got 0 errors, but I couldn't call it on program.cs (nothing happend).
tal1 and tal2 is the numbers in double form that are going to be operated ( tal1 + tal2) example.
Metod is a string that is typed by a user and choosing a operator between (+,-,* etc).
metod is used in switch case to be determined what to write line.
using MyCalculat;
namespace SwitchOP
{
public class SwCase : ReadInfo
{
public static void Cases()
{
Console.WriteLine("HEJ");
}
private double tal1 { get; set; }
private double tal2 { get; set; }
private string metod
{
get
{
return metod;
}
set
{
switch (metod) // Här används switch case metoden. Vi använder stringen metod som vi deklarerade i början.
{
case "+": // Ifall användaren har skrivit in +. Då kommer vi hit och gör följande.
Console.WriteLine("Resultat " + (tal1 + tal2)); // Skriver ut resultat samt adderar tal1 och tal2.
Console.ReadLine();
break; // Bryter switch casen och går ut ur den.
case "-": // Samma gäller här fast med minus
Console.WriteLine("Resultat " + (tal1 - tal2));
Console.ReadLine();
break;
case "*":
double res = tal1 * tal2; // Skapar en double med namn res och lägger in värdet tal1 gånger tal2.
Math.Round(res, 2, MidpointRounding.AwayFromZero); // Här avrundrar vi värdet vi multiplicerade och använder endast två decimaler i vårat resultat.
Console.WriteLine("Resultat " + (res)); // Skriver ut resultat med double res.
Console.ReadLine();
break;
case "/":
if (tal2 == 0) // om tal2 är lika med 0 går vi in i en if-sats, efter att man försökt dela med 0.
{
Console.WriteLine("Det går ej att dela med 0");
Console.ReadLine();
Console.WriteLine("Ditt andra tal var " + tal2);
Console.WriteLine("Skriv om ditt andra tal"); // Användaren får en ny chans att skriva ett andra tal.
tal2 = double.Parse(Console.ReadLine()); // Tal2 får ett nytt värde
Console.WriteLine("Resultat: " + (tal1 / tal2));
}
else // Om andra talet in är lika med 0 så kommer vi hit direkt.
Console.WriteLine("Resultat " + (tal1 / tal2));
Console.ReadLine();
break;
case "C": // Räkna ut Celsius till F
Console.WriteLine("Resultat " + (tal1 * 9 / 5 + 32));
Console.ReadLine();
break;
case "F":
tal1 = tal1 - 32;
tal1 = tal1 * 5; // räknar ut F till celsius
tal1 = tal1 / 9;
Console.WriteLine("Resultat " + (tal1));
Console.ReadLine();
break;
default:
Console.WriteLine("Hej!"); // Switch casen kommer hit och ska skriva hej om något fel uppstår ( Egentligen används inte default just nu för att if-satsen längre upp uteslår allt annat än +,-,*,/ )
Console.ReadLine();
Environment.Exit(0); // Programmet avslutas.
break;
}
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
