我正在尝试创建一个具有两个类的C#程序,这些程序将根据用户的输入做出决定,以输出使用户总是迷路的响应(例如,用户说“石头”而计算机说“纸”)。我目前在说
时出错“无法将类型'int'隐式转换为'字符串'类型” 所有案例(“案例1:”,“案例2:”,“案例3:”)。
但是我已经将“ nameClassif”定义为上面的字符串。我也有一个警告:警告CS0649:从未将字段'Player.classif'分配给该字段,并且其默认值始终为空
using System;
using static System.Console;
namespace Tes
{
class PlayerApp
{
public static void Main()
{
Player player1 = new Player();
player1.PlayerChoice = InputValue();
player1.Classif = InputValue();
Clear();
Write(player1);
Write("\n\n\n\n");
ReadKey();
}
public static string InputValue()
{
Write("Please enter rock, paper, or scissors:\t");
return ReadLine();
}
}
class Player
{
private string classif;
// constructors
public Player()
{ }
public Player(string pC)
{
PlayerChoice = pC;
}
// properties
public string PlayerChoice { get; set; }
public string Classif { get; set; }
public double SetFine()
{
if (classif == "rock")
{
WriteLine("The computer chose paper. You lose.");
}
else if (classif == "paper")
{
WriteLine("The computer chose scissors. You lose.");
}
else if (classif == "scissors")
{
WriteLine("The computer chose rock. You lose.");
}
return SetFine();
}
public string ReturnNameOfClassification()
{
string nameClassif;
switch (classif)
{
case 1: nameClassif = "rock"; break;
case 2: nameClassif = "paper"; break;
case 3: nameClassif = "scissors"; break;
default:
WriteLine("Invalid selection..." +
" I assume you chose rock... :");
nameClassif = "rock - ???"; break;
}
return nameClassif;
}
public override string ToString()
{
return "\n\n\n\t\tRock-Paper-Scissors" +
"\nThe computer chose\t" + PlayerChoice;
}
}
}
答案 0 :(得分:2)
问题是您将classif
声明为string
,但将其与int
进行了比较:
private string classif;
switch (classif)
{
case 1: nameClassif = "rock"; break; // 1 is an int, not a string!
}
简而言之:“ 5”不等于5,也不等于5。要解决此问题,您应该使用like进行比较:
switch (classif)
{
case "1": nameClassif = "rock"; break;
case "2": nameClassif = "paper"; break;
case "3": nameClassif = "scissors"; break;
default:
WriteLine("Invalid selection..." +
" I assume you chose rock... :");
nameClassif = "rock - ???"; break;
}
现在您要比较的类型与您要比较的类型相同,因此代码可以正常工作。
答案 1 :(得分:2)
使用switch
语句时,case语句中的值需要与要打开的变量的类型匹配。您正在打开classif
,它是string
,但是您的case
语句是1、2、3,它们是int
答案 2 :(得分:0)
这个:
案例1、2、3表示整数。这就是它返回错误的原因。
case "1": nameClassif = "rock"; break;
case "2": nameClassif = "paper"; break;
case "3": nameClassif = "scissors"; break;