So i wanted to make a simple dice roll game in c# with switch and case but when I start the case statements don't print anything. I hope one of you guys can help me there because as you can see I am a complete beginner.
using System;
using System.Threading;
namespace Übung
{
class MainClass
{
public static void Main(string[] args)
{
Random r = new Random();
int rnd = Random.Range(1, 7);
Console.WriteLine("Möchten sie WÜrfeln? \n ja? \n nein?");
string s = Console.ReadLine();
if (s == "ja")
{
switch (rnd)
{
case 1:
Console.WriteLine("Ihr WÜrfel hat die Zahl 1 ergeben");
break;
case 2:
Console.WriteLine("Ihr WÜrfel hat die Zahl 1 ergeben");
break;
case 3:
Console.WriteLine("Ihr WÜrfel hat die Zahl 1 ergeben");
break;
case 4:
Console.WriteLine("Ihr WÜrfel hat die Zahl 1 ergeben");
break;
case 5:
Console.WriteLine("Ihr WÜrfel hat die Zahl 1 ergeben");
break;
case 6:
Console.WriteLine("Ihr WÜrfel hat die Zahl 1 ergeben");
break;
}
}
else
{
return;
}
}
}
}
CodePudding user response:
This seems problematic:
Random r = new Random();
int rnd = Random.Range(1, 7);
Random.Range
is part of Unity3D and requires using the UnityEngine
namespace - is that what you meant to use? If not, and you're writing a plain .NET console app, you probably meant to write:
Random r = new Random();
int rnd = r.Next(1, 7);
By the way, a better way to print out the result would be to include it as part of the string you are printing, rather than using a switch case enumerating all possible values. That is, you can replace the entire switch statement with this:
Console.WriteLine($"Ihr WÜrfel hat die Zahl {rnd} ergeben");
CodePudding user response:
Use rand
as follows:
int rnd = Random.Range(1, 7);
Random.Range()
accepts arguments the first argument is inclusive and the second argument is exclusive. In our case, we want a random number between 1
and 6
inclusive both hence we pass the arguments 1
and 7
where 7
is exclusive