[英]Dice Game in C# with Switch / Case not working
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.所以我想在 c# 中用 switch 和 case 制作一个简单的掷骰子游戏,但是当我开始 case 语句时不打印任何东西。 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;
}
}
}
}
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? Random.Range
是 Unity3D 的一部分,需要使用UnityEngine
命名空间——这就是你的意思吗? If not, and you're writing a plain .NET console app, you probably meant to write:如果不是,并且您正在编写一个普通的 .NET 控制台应用程序,您可能打算编写:
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.顺便说一句,打印结果的更好方法是将其作为您正在打印的字符串的一部分包含在内,而不是使用 switch case 枚举所有可能的值。 That is, you can replace the entire switch statement with this:也就是说,您可以将整个 switch 语句替换为:
Console.WriteLine($"Ihr WÜrfel hat die Zahl {rnd} ergeben");
Use rand
as follows:使用rand
如下:
int rnd = Random.Range(1, 7);
Random.Range()
accepts arguments the first argument is inclusive and the second argument is exclusive. Random.Range()
接受 arguments 第一个参数是包含的,第二个参数是排除的。 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在我们的例子中,我们想要一个介于1
和6
之间的随机数,因此我们通过 arguments 1
和7
,其中7
是唯一的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.