c#公共静态字符串,并非所有代码路径都返回值
我还不完全理解方法,我也不知道为什么会发生这种情况。。。我试图让我的代码将int改为words,我认为这是一条路要走c#公共静态字符串,并非所有代码路径都返回值,c#,string,return,C#,String,Return,我还不完全理解方法,我也不知道为什么会发生这种情况。。。我试图让我的代码将int改为words,我认为这是一条路要走 namespace ConsoleApplication9 { class Program { static void Main(string[] args) { Random r = new Random(); Console.WriteLine("Hi wanna play roc
namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
Random r = new Random();
Console.WriteLine("Hi wanna play rock paper scissors?<press enter to continue>");
Console.ReadKey();
int user = 0;
int ai = r.Next(1, 4);
Console.WriteLine("Pick what youll show! (1-rock, 2-paper, 3-scissors) and press enter");
user = Convert.ToInt32(Console.ReadLine());
if (user > 3)
{
Console.WriteLine("ERROR! your number must be <= 3. <Press enter to close the program>");
goto end;
}
if (user == ai)
{
Console.WriteLine("Its a draw! <press enter to continue>");
goto end;
}
Console.WriteLine(user);
end:
Console.ReadKey();
}
public static string ntw (int user) //ntw: not all code paths return a value
{
if (user == 1)
return "rock";
if (user == 2)
return "paper";
if (user == 3)
return "scissors";
}
}
}
命名空间控制台应用程序9
{
班级计划
{
静态void Main(字符串[]参数)
{
随机r=新随机();
控制台。WriteLine(“嗨,想玩石头剪刀吗?”);
Console.ReadKey();
int user=0;
int ai=r.Next(1,4);
Console.WriteLine(“选择要显示的内容!(1-rock,2-paper,3-剪刀)并按enter键”);
user=Convert.ToInt32(Console.ReadLine());
如果(用户>3)
{
控制台写入线("错误!您的数字必须是您的方法的返回类型是string
。这意味着您的方法应该始终返回一些字符串值。在当前的实现中,当用户变量的值是1
或2
或3
时,它将返回一些字符串。如果您使用值25
调用此方法会怎么样?编译器不知道该做什么
如果用户值不是1
或2
或3
public static string ntw (int user)
{
if (user == 1)
return "rock";
if (user == 2)
return "paper";
if (user == 3)
return "scissors";
return string.empty; // Here i am returning an empty string.
}
您还可以使用switch语句,在这种情况下,如果用户不是1、2或3:,则默认值将为您提供Null或空字符串。)
如果值必须在1..3范围内(并且返回字符串。空的字符串没有意义),则可以编写:
public static string ntw (int user)
{
if (user == 1)
return "rock";
if (user == 2)
return "paper";
if (user == 3)
return "scissors";
throw new ArgumentException("Invalid choice");
}
并在程序中的某个地方处理异常。如果user
不是1、2或3怎么办?1.请不要使用goto
。2发布代码时,请仔细检查缩进的一致性和可读性。您确实应该使用缩进。可能重复或返回字符串。空:)。
public static string ntw (int user)
{
if (user == 1)
return "rock";
if (user == 2)
return "paper";
if (user == 3)
return "scissors";
throw new ArgumentException("Invalid choice");
}