Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

c# - C#如何在按下回车键时停止while循环(C# How to stop while loop when enter pressed)

I have a homework where I have to make a program that asks numbers for ten times in a loop and in the end gives the sum of those ten numbers.

(我有一个家庭作业,我必须制作一个循环询问十次数字的程序,最后给出十个数字的总和。)

But it also must be possible to stop the loop and give the sum of numbers when enter is pressed.

(但是也必须有可能停止循环并在按下Enter键时给出数字的总和。)

I have tried something like this in while loop, but it didn't also work:

(我在while循环中尝试过类似的方法,但是它也没有用:)

if( Console.KeyAvailable && Console.ReadKey( true ).Key == ConsoleKey.Enter ) break;

(if(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Enter)中断;)

Can anyone suggest solutions?

(谁能建议解决方案?)

Thanks in advance!

(提前致谢!)

           {
            int i = 0;
            int number;
            string number_s;
            int sum = 0;


            while (i < 10)
            {
                { 
                i++;

                Console.WriteLine("Enter number:"); 
                number_s = Console.ReadLine(); 
                Int32.TryParse(number_s, out number);

                    sum += number;
                }
            }
           Console.Write("Sum is: {0}", sum);
          }
  ask by Lilian translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use if statement to check that input is not command to stop:

(您可以使用if语句来检查输入不是命令停止:)

number_s = Console.ReadLine();
if (number_s == "stop")
{
    i = 11;
}
else
{
    int.TryParse(number_s, out number);
    sum += number;
    i++;
}

Then when You write stop instead of number, loop will finished.

(然后,当您编写停止而不是数字时,循环将结束。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...