繁体   English   中英

如何在一种情况下对字符串输入使用相同的变量,在另一种情况下使用 int 输入? (C#)

[英]How to use same variable for string input in one case, and int input in another case? (C#)

快速问题如何在 case 中使用相同的变量进行字符串输入,在另一种情况下使用 int 输入。 这就是我的意思,我有一个问题,我需要不断插入数字,然后将这些数字的相加放入另一个变量中。 这个插入是在 do while 循环中,为了退出循环并显示这些数字的总和,我需要输入“OK”或“ok”。 我有一个问题,我不知道如何将字符串变量用于 int 输入。

这是我的代码:

string input= "";
            int sum = 0;
            do
            {
                Console.WriteLine("Insert the number or OK (ok) for exit: ");
                input = Console.ReadLine();

                sum += Convert.ToInt32(input); 
// this is where I get the error Input string was not in the correct fromat

            } while (input != "OK" && input != "ok");

            Console.WriteLine(sum)

如果有人知道如何帮助我解决这个问题,我将不胜感激。

首先确定用户是否使用int.TryParse()输入了整数,如果用户输入了整数,则将其添加到sum变量中,否则检查字符串

do
{
    Console.WriteLine("Insert the number or OK (ok) for exit: ");
    input = Console.ReadLine();
    //This will add number only if user enters integer.
    if(int.TryParse(input, out int number)
        sum += number

 } while (input != "OK" && input != "ok"); 

在尝试转换为数字之前,您必须测试 OK,因为 OK 不会转换为数字

        string input= "";
        int sum = 0;
        while(true)
        {
            Console.WriteLine("Insert the number or OK (ok) for exit: ");
            input = Console.ReadLine();

            if("OK".Equals(input, StringComparison.OrdinalIgnoreCase)) //do a case insensitive check. Note that it's acceptable to call methods on constants, and doing a string check this way round cannot throw a NullReferenceException
              break;//exit the loop

            sum += Convert.ToInt32(input); 

        } 

        Console.WriteLine(sum);

如果用户输入 OK 以外的输入,您仍然会收到错误消息,该输入无法转换为数字,但这是您当前问题的症结所在。 我会把处理其他垃圾留给你作为练习......

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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