简体   繁体   中英

C# How to stop console program waiting for input on the next line?

So I am just starting out and I am creating a console program where the user will enter an int. It should continue to ask for an int until they enter "ok". When they enter "ok" it should then add up all the numbers they entered.

The problem I am having is, when it asks the user for input, I enter a number and press enter. It then moves to the next line and awaits input again. Inputing a number on the next line allows the program to continue working. How do I get the program to take the first input and continue from there?

Code below, I hope my question makes sense.


class Program
{
    static void Main(string[] args)
    {
        bool tag = true;
        List<int> numbers = new List<int>();
        while (tag == true)
        {
            Console.Write("Please enter a number or 'ok' to end: ");
            if (Console.ReadLine().Equals("ok"))
            {
                tag = false;
            }
            else
            {
                int numb = Int32.Parse(Console.ReadLine());
                numbers.Add(numb);
            }
        }

        int total = 0;
        foreach (int n in numbers)
        {
            total = total + n;
        }
        Console.WriteLine("All numbers added together equals: " + total);
    }
}

You should read only once per iteration from the console.

//[...]
while (tag == true)
{
    Console.Write("Please enter a number or 'ok' to end: ");
    var input = Console.ReadLine();
    if (input.Equals("ok"))
    {
        tag = false;
    }
    else
    {
        int numb = Int32.Parse(input);
        numbers.Add(numb);
    }
}
//[...]

Each time you call Console.ReadLine , the user must enter input - because you call it once to compare to "Ok" and once more to parse, the user has to enter a number twice.

You can go even further and omit your tag variable if you use the input as loop condition:

var input = "";
var numbers = new List<int>();
while((input = Console.ReadLine()) != "ok")
{
    numbers.Add(int.Parse(input));
}

All of this is without any error handling if the user enters something that's neither "ok" nor a valid integer. For this you should have a look at int32.TryParse .

Just adding to the possible number of solutions to the specified problem (adding a bit of recursion to the mix):

class Program
{
    private static List<int> numbers = new List<int>();
    private static int Prompt()
    {
        //1. Promt the user for input
        Console.Write("Please enter a number or 'ok' to end: ");
        var input = Console.ReadLine().ToLower();
        int number = 0;
        if (input.Equals("ok"))
        {
            //2. Do nothing and end the Program
        }
        else
        {
            //3. Ty to parse to int and append to the list
            if(int.TryParse(input, out number))
            {
                //4. Add the number to the list (no more needed for sum but still if you want to maintain the order of numbers added :))
                numbers.Add(number);                    
            }
            else
            {
                //5. In case of junk input
                Console.WriteLine("Invalid input.");
            }
            number += Prompt();
        }
        return number;
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Total of the Inout Numbers: " + Prompt());

        Console.ReadKey();
    }
}

Hope this helps and adds another perspective :)

So, by the time I finished my answer (I decided to let Visual Studio update...) there was already an answer pointing out the issue (reading from the console multiple times instead of storing the result in a variable). I just decided to post the code anyway so you could see another approach that might be valid to you (not storing all the numbers).

As you can see, I'm ignoring here anything that is not a int or OK.

class Program
 {
     static void Main(string[] args)
     {
         var total = 0;
         Console.WriteLine("Please enter a number or 'ok' to end: ");
         bool numberRead;
         string line;
         do
         {
            line = Console.ReadLine();
            if(numberRead = int.TryParse(line, out int number))
                total += number;
         } while (numberRead && line?.ToLower() != "ok");

         Console.WriteLine("All numbers added together equals: " + total);
     }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM