【发布时间】:2021-02-13 20:52:36
【问题描述】:
namespace C2360_Ch07_Console1_InRange
{
class InRange
{
static void Main(string[] args)
{
Console.WriteLine("Num:");
String theLine;
theLine = Console.ReadLine();
try
{
theLine = Convert.ToInt32(Console.ReadLine());//cant convert
}
catch (FormatException)
{
Console.WriteLine("Input string was not in a correct format.");
}
IsWithinRange(theLine);
}
static void IsWithinRange(String theLine)
{
int Line1;
Int32.TryParse(Console.ReadLine(), out Line1);
try
{
if ((Line1 < 1) || (Line1 > 10))
{
throw new OverflowException();
}
}
catch (OverflowException)
{
Console.WriteLine("number must be between 1 and 10.");
}
Console.ReadLine();
}
}
}
我想要做的是 convert string 到 integer 以验证 Main 和 IsWithinRange 方法。当我将theLine 转换为Int32.TryParse 时,我收到一个错误,评论所在的位置。这有可能吗?
有什么帮助吗?
【问题讨论】:
-
你确定错误出现在 Int32.TryParse 而不是之前的 Convert.ToInt32?
-
错误在 Convert.ToInt32 为什么?
-
我猜你正在输入一个数字,然后再次按 Enter 键,因为没有任何反应:这是因为你为
theLine两次调用了Console.ReadLine()/跨度> -
很抱歉,她要我们串起来; theLine = Console.ReadLine();在主要。然后将 theLine 传递给 Main 中的 Convert.Int32。您需要使 IsWithinRange 具有 String 参数。当您从 Main 调用时,将 theLine 传递给该函数。然后你可以在 IsWithinRange 中调用 TryParse 时使用该字符串参数。
-
首先将
theLine设置为字符串-String theLine = Console.ReadLine();。然后,您尝试通过再次调用 ReadLine 将其设置为整数 - `theLine = Convert.ToInt32(Console.ReadLine())'。