gpt4 book ai didi

c# - C#—在Convert.ToInt32(...)之后,循环将不接受非数字输入

转载 作者:行者123 更新时间:2023-12-02 10:50:46 24 4
gpt4 key购买 nike

当我尝试输入退出字符串xxx时,为什么会引发异常?它在循环中以的方式工作,但在循环中不与 do ...一起使用。

转换为整数后,字符串变量仅允许我使用数字字符(如-999)退出 do ...,而循环。但是我想使循环控制变量成为“quit”而不是数字之类的词。我怎样才能做到这一点?

这是我的代码。

using System;
namespace StringInputPractice
{
class StringInputPractice
{
static void Main()
{
// Declarations

string inValue;
int first;
int second;
int sum;

do
{
Console.Write("\nEnter the first number. (Type \"xxx\" to exit): ");
inValue = Console.ReadLine();

first = Convert.ToInt32(inValue); //@@@@@
Console.Write("\nEnter the second number. (Type \"xxx\" to exit): ");
inValue = Console.ReadLine();
second = int.Parse(inValue);

sum = first + second;

Console.WriteLine("\nThe sum of {0} and {1} is {2}.", first,
second, sum);

/* Things I've tried inside do { } and that don't work */

//inValue = "";
//inValue = null;
//inValue = inValue.ToString();
//inValue = first.ToString();
//inValue = second.ToString();
}

while (inValue != "xxx"); /*If you enter a non-numeric string,
* an exception is thrown at
* @@@@@ above.
*/

Console.ReadLine();
}
}
}

最佳答案

试试这个:使用int.TryParse代替Convert.ToInt32

public void myfun()
{
string inValue;
int first;
int second;
int sum;

do
{
Console.Write("\nEnter the first number. (Type \"xxx\" to exit): ");
inValue = Console.ReadLine();

if (int.TryParse(inValue, out first))
{
// first = Convert.ToInt32(inValue); //@@@@@
Console.Write("\nEnter the second number. (Type \"xxx\" to exit): ");
inValue = Console.ReadLine();
if(int.TryParse(inValue, out second))
{
// second = int.Parse(inValue);

sum = first + second;

Console.WriteLine("\nThe sum of {0} and {1} is {2}.", first,
second, sum);
}
}
/* Things I've tried inside do { } and that don't work */

//inValue = "";
//inValue = null;
//inValue = inValue.ToString();
//inValue = first.ToString();
//inValue = second.ToString();
}

while (inValue != "xxx"); /*If you enter a non-numeric string,
* an exception is thrown at
* @@@@@ above.
*/

Console.ReadLine();
}

关于c# - C#—在Convert.ToInt32(...)之后,循环将不接受非数字输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9476694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com