【发布时间】:2018-02-21 00:08:23
【问题描述】:
我正在尝试制作一个石头、剪纸、剪刀游戏,我想我差不多完成了,但我不断收到“无法将类型“字符串”隐式转换为“整数”。我已经浏览了这个网站,但我不知道如何修复它。这是我的代码
int userChoice = int.Parse(RadioButtonList1.SelectedValue);
Random r = new Random();
int computerChoice = r.Next(3);
if (computerChoice == 1)
{
if (userChoice = "rock") {
resultLabel.Text = Convert.ToString("Computer chose Rock too. Tie!");
}
if (userChoice = "paper")
{
resultLabel.Text = "Computer chose Rock. You win!";
}
if (userChoice = "scissors")
{
resultLabel.Text = "Computer chose Rock. You Lose!";
}
}
else if (computerChoice == 2)
{
if(userChoice = "rock") {
resultLabel.Text = "Computer chose Rock. You win!";
}
if (userChoice = "paper")
{
resultLabel.Text = "Computer chose Paper too. Tie!";
}
if (userChoice = "scissors")
{
resultLabel.Text = "Computer chose Scissors. You lose!";
}
}
else if (computerChoice == 3)
{
if (userChoice = "rock")
{
resultLabel.Text = "Computer chose Rock. You Lose!";
}
if (userChoice = "paper")
{
resultLabel.Text = "Computer chose Paper. You win!";
}
if (userChoice = "scissors")
{
resultLabel.Text = "Computer chose Scissors too. Tie!";
}
}
}
}
【问题讨论】:
-
你为什么要在
string上打电话给Convert.ToString()? -
这条线
userChoice = "rock"有几点是错误的。首先,userChoice是一个 int,第二个 '=' 是一个赋值运算符(你想要相等运算符==)。您收到错误消息的原因是因为您基本上试图将字符串分配给 int。 -
我可以看到您的代码存在一些问题。第一个问题是
userChoice被定义为int并且您尝试与多个if语句中的字符串进行比较。第二个问题是(我希望这只是一个错字)是几个if语句正在执行赋值操作而不是比较操作。您可能想使用enum来清理您的逻辑。 -
我们不知道如何帮助您,因为我们不知道
RadioButtonList1.SelectedValue包含什么。它包含什么? -
你应该指出你得到异常的地方
标签: c# string visual-studio int