while(true)循环中的system.formatexception

时间:2017-06-15 03:39:17

标签: c#

主题有点问题: 编写一个程序并不断要求用户输入一个数字或" ok"退出。计算所有先前输入的数字的总和,并将其显示在控制台上。

这是我的代码:

    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);
    }

当我点击确定时,它会终止。 当我点击数字并输入时,它显示system.formatexception:输入字符串的格式不正确。 我知道其中一个解决方案是

    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);

也许我的代码看起来有些小,但为什么我的代码错了?

7 个答案:

答案 0 :(得分:0)

原因input将是"确定"。无法将其转换为整数。

  1. 首先,您必须将第一个输入值存储到其他变量中。
  2. 然后将该字符串转换为整数并获得求和。

    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);
    
  3. 如果有任何问题请告诉我。

答案 1 :(得分:0)

试试这个:

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);
}

这里我只是将用户输入的输入存储在一个变量中,并在进一步的过程中使用该变量。

在你的第一个代码中你输入了两次,第一个是IF条件,第二个是解析,这可能会导致问题。

答案 2 :(得分:0)

执行此操作的正确方法是使用int.TryParse进行从string到数字的转换。 TryParse尝试将字符串转换为数字,但如果它不能这样做(例如,字符串包含的不仅仅是数字),它将正常失败而不是导致异常。如果输入非FormatException之外的非数字,则到目前为止的其他答案都将导致未处理"ok"。通过使用int.TryParse,您可以处理有效数字的情况,以及无效的情况,然后提醒用户。以下是代码上下文中的示例:

// 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());

这是更好的,因为您知道除了自己验证之外,您无法控制用户的输入,因此最好推测性地转换数字并在不触发异常的情况下提醒成功或失败。使用try / catch块包装所有内容并不是一个合适的解决方案。

答案 3 :(得分:0)

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, i.e. 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

答案 4 :(得分:0)

尝试:)

[MainThread  ] [WARNI]  Failed to see startup log message; retrying...
[MainThread  ] [WARNI]  Tika server returned status: 422

编写程序并不断要求用户输入数字或单击“确定”退出。计算所有先前输入的数字的总和,并将其显示在控制台上。快乐编码

答案 5 :(得分:0)

Input String     : abc=cde,dfe=lk,f,sss=f,d,s

Final properties : 
key = dfe :: value = lk,f
key = sss :: value = f,d,s
key = abc :: value = cde

答案 6 :(得分:0)

这是一种实现方法。我只是在学习这样做!

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();
    }
}