gpt4 book ai didi

c# - Console.WriteLine 出于某种原因重复自身

转载 作者:太空宇宙 更新时间:2023-11-03 18:57:56 27 4
gpt4 key购买 nike

我是 C# 的绝对初学者并且编写了这段代码,但输出让我感到困惑:

static void PlayerInfo() //Asking information about the player
{
Console.Write("Type your name: ");
string inputName = Console.ReadLine();

if (inputName.Length < 2)
PlayerInfo();
else
playerName = inputName;

Console.WriteLine("Hello " + playerName + "!");
}

如果我先输入 J,它会再次询问我,直到我输入至少 2 个字符。如果我之后输入 John Doe,它会给我两次输出 Console.WriteLine("Hello "+ playerName + "!");

我不明白为什么,它在控制台中看起来像这样:

Type your name: J         //The length is smaller than 2
Type your name: John Doe //Restart the function and type a valid length
Hello John Doe! //This is OK
Hello John Doe! //Why a second print?

使用递归方法可能不是最佳做法。我这样做只是为了学习语言。

最佳答案

问题是由于递归引起的。
你调用 PlayerInfo() 两次,所以你得到两次输出,就这么简单。
如果您输入“A”,然后输入“B”,然后输入“John”,您将获得 3 次输出,依此类推。

答案就是去掉递归。如果您希望在收到有效输入之前一直提示,那么一个解决方案是 while 循环:

void Main()
{
PlayerInfo();
}

static void PlayerInfo()
{
string inputName = string.Empty;

// This will loop until inputName is longer than 2 characters
while (inputName.Length < 2)
{
Console.Write("Type your name: ");
inputName = Console.ReadLine();
}

// Now that inputName is longer than 2 characters it prints the result only once
Console.WriteLine("Hello " + inputName + "!");
}

例子:

Type your name: A
Type your name: B
Type your name: John
Hello John!

See it working on .NET Fiddle

关于c# - Console.WriteLine 出于某种原因重复自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41189324/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com