我有一个函数,它要求用户输入,它将被解析为int,并将用于创建金字塔。
我知道我必须使用某种循环,我尝试过do/while循环,但我似乎不明白。在do/while之外,我不能在Console.Write上声明n,如果我在do/while的下面声明它,while条件将不会接受它,因为它超出了作用域。这么说似乎很简单,做(请求输入并分配给n)而不是(n <=0),但我做不到。
我也有一个想法,我尝试过,只要n是<=0,它就可以在内部运行这个函数,但是它可以无限地运行这个函数。我不确定我是否走上了正确的轨道,但我现在感到迷失了。
static void Pyramid()
{
Console.Write("Choose a pyramid height: ");
int n = Int32.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
Console.Write(" ");
}
for (int j = 0; j < i + 2; j++)
{
Console.Write("#");
}
Console.Write(" ");
for (int j = 0; j < i + 2; j++)
{
Console.Write("#");
}
Console.WriteLine();
}
}
发布于 2019-09-09 00:14:12
它应该能发挥作用:
int n;
do
{
Console.Write("Choose a pyramid height: ");
n = Int32.Parse(Console.ReadLine());
if ( n <= 0) Console.WriteLine("Value must be greater than 0.");
}
while ( n <= 0 );
发布于 2019-09-09 00:11:04
如果数字无效,只需使用无限while循环,并使用continue
:
static void Pyramid()
{
while(true)
{
Console.Write("Choose a pyramid height: ");
int n = Int32.Parse(Console.ReadLine());
if (n <= 0)
{
Console.Error.WriteLine("That's an invalid number");
continue;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
Console.Write(" ");
}
for (int j = 0; j < i + 2; j++)
{
Console.Write("#");
}
Console.Write(" ");
for (int j = 0; j < i + 2; j++)
{
Console.Write("#");
}
Console.WriteLine();
}
}
}
发布于 2019-09-09 00:23:09
我们来提取方法。我们应该实现2检查:
"bla-bla-bla"
不是整数)-123
)代码:
public static int ReadInteger(string prompt,
Func<int, bool> validation = null,
string validationMessage = null) {
int result;
while (true) {
if (!string.IsNullOrEmpty(prompt))
Console.WriteLine(prompt);
string input = Console.ReadLine();
if (!int.TryParse(input, out result))
Console.WriteLine("Sorry, your input is not a valid integer value. Please, try again.");
else if (validation != null && !validation(result))
Console.WriteLine(string.IsNullOrEmpty(validationMessage)
? "Sorry the value is invalid. Please, try again"
: validationMessage);
else
return result;
}
}
然后您可以轻松地使用它:
int n = ReadInteger(
"Choose a pyramid height:",
(value) => value > 0,
"Pyramid height must be positive. Please, try again.");
//TODO: your code here to draw the pyramid of height "n"
请注意,您也可以轻松地限制上限(高度金字塔1000000000
将挂起计算机):
int n = ReadInteger(
"Choose a pyramid height:",
(value) => value > 0 && value <= 100,
"Pyramid height must be in [1..100] range. Please, try again.");
https://stackoverflow.com/questions/57850025
复制相似问题