简体   繁体   中英

system.formatexception in while(true) loop

The subject is a little problem: Write a program and continuously ask the user to enter a number or "ok" to exit. Calculate the sum of all the previously entered numbers and display it on the console.

Here is my code:

    var sum = 0;
    while (true)
    {
        Console.WriteLine("Enter a number or ok to exit:");
        if (Console.ReadLine() == "ok") break;
        sum += Convert.ToInt32(Console.ReadLine());
        Console.WriteLine(sum);
    }

When I tap ok, it terminate. When I tap number and enter, it shows system.formatexception:The input string is not in the correct format. I know one of the solution is

    var sum = 0;
    while (true)
    {
        Console.Write("Enter a number (or 'ok' to exit): ");
        var input = Console.ReadLine();
        if (input.ToLower() == "ok")
            break;
        sum += Convert.ToInt32(input);
    }
    Console.WriteLine("Sum of all numbers is: " + sum);

Maybe My code looks a little weired, But Why is my code wrong?

Reason is input will be "ok". Can not convert that into an integer.

  1. first you have to store the first input value into other variable.
  2. then convert that string into integer and get summation.

     var sum = 0; while (true) { Console.Write("Enter a number (or 'ok' to exit): "); var input = Console.ReadLine(); int newVariable = 0; if (input.ToLower() != "ok") { newVariable = Convert.ToInt32(input); } input = Console.ReadLine(); if (input.ToLower() == "ok"){ break; sum += newVariable; } } Console.WriteLine("Sum of all numbers is: " + sum);

If there any problem here please let me know.

Try this:

var sum = 0;
while (true)
{
        Console.WriteLine("Enter a number or ok to exit:");
        String ans = Console.ReadLine();
        if (ans == "ok" || ans.ToLower() == "ok") break;
        sum += Convert.ToInt32(ans);
        Console.WriteLine(sum);
}

Here I've just store input entered by user in one variable and use that variable in further process.

In your first code you have take input two times, first one is in IF condition and second in parsing, that may cause the problem.

The correct way to do this is to use int.TryParse for your conversion from a string to a number. TryParse attempts to convert the string to a number, but if it cannot do so (for example, the string contains more than just numeric digits) it will fail gracefully instead of causing an exception. The other answers so far will all cause an unhandled FormatException if something non-numeric is entered other than "ok" . By using int.TryParse you can handle the case where it's a valid number, as well as the case where it is invalid, and then alert the user. Here's an example within the context of your code:

// I prefer using concrete types for numbers like this, so if anyone else
// reads it they know the exact type and numeric limits of that type.
int sum = 0;
int enteredNumber = 0;
while (true)
{
    Console.Write("Enter a number (or 'ok' to exit): ");
    var consoleInput = Console.ReadLine();
    if (consoleInput.ToLower() == "ok")
        break;

    if(int.TryParse(consoleInput, out enteredNumber))
    {
        sum += enteredNumber;
    }
    else
    {
        Console.WriteLine("You entered '" + consoleInput + "', which is not a number.");
    }
}

Console.WriteLine("Sum of all numbers is: " + sum.ToString());

This is better because you know you have no control over the user's input other than to validate it yourself, and so it's better to speculatively convert the number and be alerted to success or failure without triggering an exception. Wrapping everything with a try/catch block is not a proper solution.

Your first code example, as rightly pointed out in the comments, reads a line, tests it for 'ok', then throws it away, reads another line, and uses that to add to the sum, which is not what you wanted.

After some quick research, I would say the most concise way to handle this in C# is probably something like your second code example. In F# I was able to come up with the following examples (one is a loop, the other uses sequences, ie IEnumerable<_> s) but I found no concise way to get the same with C# and LINQ…

let inputLoop () =
    let rec aux sum =
        match stdin.ReadLine () with
        | "ok" -> sum
        | s -> aux (sum + int s)
    stdout.WriteLine (aux 0 |> string)

let inputSeq () =
    fun _ -> stdin.ReadLine ()
    |> Seq.initInfinite
    |> Seq.takeWhile (fun s -> s <> "ok")
    |> Seq.sumBy int
    |> string
    |> stdout.WriteLine

Try it :)

var sum = 0;
while (true)
        {
           Console.Write("Enter a number:  or ok to exit : ");
            String input = Console.ReadLine();
            if (input == "ok" || input.ToLower() == "ok") break;
            if(string.IsNullOrWhiteSpace(input))
            continue;
            sum += Convert.ToInt32(input);
        }
        Console.WriteLine("Total Result: " + sum);

Write a program and continuously ask the user to enter a number or "ok" to exit. Calculate the sum of all the previously entered numbers and display it on the console. Happy Coding

var sum = 0;
while (true)
{
    Console.Write("Write number or write \"ok\" for exit: ");
    var input = Console.ReadLine();

    if (input.ToLower() != "ok")
    {
        sum += Convert.ToInt32(input);
        continue;
    }
    break;
}
Console.WriteLine("All sum: " + sum + ".");

This is one way to do it. I'm just learning to do this!

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter number to know the sum or press ok to exit and display the sum");
        int sum = 0;
        while (true) // to run the program continously asking user input
        {
            Console.WriteLine("Enter Number: ");
            var input = Console.ReadLine(); // takes user input
            if (input.ToLower() == "ok") // compares user input to string ok
                break; //if user input is ok, breaks the loop and sum is displayed
            var inputInInt = Convert.ToInt32(input); // if user input is int, continues to convert it to integer
            sum += inputInInt; // user input in interger is added to sum
            
        }
        Console.WriteLine("The sum of entered numbers is: " + sum);
        Console.ReadLine();
    }
}

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