我的目标是向用户询问他们想要打印的三张预先确定的ascii艺术图片中的哪一幅以及他们想要打印多少次。我的问题是它打印的次数比选择的数量多50倍。我尝试转换打印变量,但这不起作用。我对C#很新,所以我为任何重大的基本错误道歉。
Console.WriteLine("Would you like to print picture 1, 2, or 3?");
int print = 0;
string choice = "";
while (choice != "end")
{
choice = Console.ReadLine();
switch (choice)
{
case "1":
Console.WriteLine("How many times would you like to print it");
print = Convert.ToInt32(Console.ReadLine());
while (print > 10)
{
Console.WriteLine(cocaCola);
print -= 1;
}
break;
case "2":
Console.WriteLine("How many times would you like to print it");
print = Convert.ToInt32(Console.ReadLine());
while (print > 10)
{
Console.WriteLine(beam);
print -= 1;
}
break;
case "3":
Console.WriteLine("How many times would you like to print it");
print = Convert.ToInt32(Console.ReadLine());
while (print > 10)
{
Console.WriteLine(liberty);
print -= 1;
}
break;
default:
Console.WriteLine("You chose nothing");
break;
}
Console.WriteLine("Choose again, or type \"end\" to exit");
答案 0 :(得分:1)
它不再打印50次;它的打印时间恰好是48次。
您正在读取一个字符并将其unicode值分配给整数。例如,用户键入“1”,即字符1
。它的Unicode值是49.你为你的int print
分配49,你就是。字符实际上是一个小的或小的整数,它本质上是某个字符表的索引。
在Unicode中,与ASCII一样,“0”是十进制48,“1”是十进制49,依此类推,最多为“9”。这就是48来自哪里。
你想要做的是更像这样的事情。首先,你要阅读整行,而不仅仅是第一个字符;如果用户键入“12”怎么办?然后你需要解析字符串“1”(或“12”,这是两个字符)来得到整数'1'或'12'。
事实上,这正是你在这一行上所做的:
print = Convert.ToInt32(Console.ReadLine());
因此,请在每个地方使用该版本print = Console.Read();
第二个错误:你将print设置为一些可能小的数字,比如说用户键入“4”,所以它是4
。然后你在大于 10时循环 - 但它永远不会大于10.你想在大于零时循环:
while (print > 0)
{
Console.WriteLine(cocaCola);
print -= 1;
}
你需要在三个地方解决这个问题。
三个地方比你想要处理的更多。所以这是另一回事:你可以通过在switch语句中设置一个变量来简化这段代码,并且只编写一次循环(你可以通过其他方式进一步简化它,但让我们一步一步): / p>
Console.WriteLine("Would you like to print picture 1, 2, or 3?");
int print = 0;
string choice = "";
while (choice != "end")
{
choice = Console.ReadLine().Trim();
String thingToPrint = null;
switch (choice)
{
case "1":
thingToPrint = cocaCola;
break;
case "2":
thingToPrint = beam;
break;
case "3":
thingToPrint = liberty;
break;
}
if (thingToPrint != null)
{
Console.WriteLine("How many times would you like to print it");
print = Convert.ToInt32(Console.ReadLine());
while (print > 0)
{
Console.WriteLine(thingToPrint);
print -= 1;
}
}
else
{
Console.WriteLine("You chose poorly. Try again.");
}
Console.WriteLine("Choose again, or type \"end\" to exit");
}