只是试图制作一个抛硬币游戏,但也试图将等于随机数 0 或 1 的硬币转换为字符串类型"正面"或"反面"。编程新手,所以请不要判断它是否看起来很业余。谢谢。
namespace TestCoin2
{
class Program
{
static void Main(string[] args)
{
int coin;// this will hold my random int numbers.
string userInput;// This will hold all my user input/ answers.
Console.WriteLine("Hello, Pick Heads or Tails:");
userInput =Console.ReadLine();
Random rng = new Random();
coin = rng.Next(0, 2);
string myString2;
string myString;
if (coin == 0)
{
myString = coin.ToString("heads");
}
else if (coin == 1)
{
myString2 = coin.ToString("tails"); <error under myString2
}
if (myString && userInput == "heads")
{
Console.WriteLine("You picked Right! Heads! YOU WIN!");
}
else if (coin == 1 && userInput == "Tails")
{
Console.WriteLine("You picked Right! Tails! YOU WIN!");
}
else
{
Console.WriteLine("You picked Wrong! it was..." + myString); <error
}
Console.ReadLine();
}
}
}
因为您要将固定数量的 int
s 转换为其他内容。最好的办法是定义一个enum
。
public enum CoinSide
{
Heads = 0,
Tails = 1
}
然后,您只需将int
投射到enum
,它将输出侧面。
var rng = new Random();
var coin = rng.Next(0,2);
Console.WriteLine((CoinSide)coin);
如果您需要比较它们,您可以使用它。
if (((CoinSide)coin).ToString() == "Heads")
Console.WriteLine("Winner");
完整解决方案
//Accept user input
Console.WriteLine("Hello, Pick Heads or Tails:");
var userInput = Console.ReadLine();
//Create and flip the coin
var rng = new Random();
var coin = (CoinSide)rng.Next(0, 2);
//Compare input to coin
if (coin.ToString() == userInput)
Console.WriteLine("You picked Right! {0}! YOU WIN!", coin);
else
Console.WriteLine("You picked Wrong! it was... {0}", coin);
您可以像这样简单地使用 ?:
运算符:
myString = coin == 0 ? "heads" : "tails";
为了使其更具可读性,您可以使用如下所示的枚举。您可以使用您喜欢的任何数字代替 0 和 1。在类中定义枚举并在方法中使用它。
public enum CoinSides{ Heads = 0, Tails = 1}
您可以重写完整的代码,如下所示,
namespace TestCoin2
{
class Program
{
public enum CoinSides { Heads = 0, Tails = 1 }
static void Main(string[] args)
{
string userInput;// This will hold all my user input/ answers.
Console.WriteLine("Hello, Pick Heads or Tails:");
userInput = Console.ReadLine();
int coin;// this will hold my random int numbers.
Random rng = new Random();
coin = rng.Next(0, 2);
if (coin == Convert.ToInt32(CoinSides.Heads) && userInput == CoinSides.Heads.ToString("D"))
{
Console.WriteLine("You picked Right! Heads! YOU WIN!");
}
else if (coin == Convert.ToInt32(CoinSides.Tails) && userInput == CoinSides.Tails.ToString("D"))
{
Console.WriteLine("You picked Right! Tails! YOU WIN!");
}
else
{
Console.WriteLine("You picked Wrong! it was..." + myString);
}
Console.ReadLine();
}
}
}