gpt4 book ai didi

c# - 开关盒忽略 Console.ReadLine()

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

我正在帮助一位初学 c# 的 friend ,我们遇到了一个奇怪的问题。

第 31 行的 læn = Console.ReadLine() 被跳过。这会导致第 32 行的 .Parse 抛出错误。

如果我们在第一个之后添加一个额外的 læn = Console.ReadLine(),它就会开始工作。

static void Main(string[] args)
{
double areal, læn1, høj1 = 0;
int figur;
string tekst, læn, høj;

tekst = ("Du skal nu vægle en figur.");
tekst += ("\nTryk 1 for rektangel");
tekst += ("\nTryk 2 for cirkel");
tekst += ("\nTryk 3 for en retvinklet trekant");
tekst += ("\nValg: ");
Console.Write("{0}", tekst);
figur = Console.Read();
switch (figur)
{
case '1':
{
Console.WriteLine("Du har valgt en rektangel. \nHvad er længden: ");
læn = Console.ReadLine(); //Line 31
læn1 = double.Parse(læn); //Line 32

Console.WriteLine("hvad er højden?");
høj = Console.ReadLine();
høj1 = double.Parse(høj);

areal = læn1 * høj1;
Console.WriteLine("\n{0} * {1} = {2}", læn, høj1, areal);

Console.ReadKey();
}
break;

default:
Console.WriteLine("Du har ikke valgt 1,2 eller 3");
Console.ReadKey();
break;
}
}

最佳答案

文档来自 Console.Read状态:

The Read method blocks its return while you type input characters; it terminates when you press the Enter key.

这意味着它只会在您按下 Enter 时返回一个值,无论您输入了多少内容。

由于您的下一条语句是 Console.ReadLine() 并且流中仍有一行结束等待读取(因为您按了 Enter,但只处理了按下键),“吃掉”该语句。

考虑使用 Console.ReadKey()相反。

关于c# - 开关盒忽略 Console.ReadLine(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26972653/

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