Java while循环中的扫描仪
我可以在C中使用什么?没有扫描仪 这篇文章没有解释如何用C语言制作扫描仪。它只解释了如何解析用户的输入,使其仅为整数。让我们为它提取一个ReadInteger方法。请注意,我们使用int.TryParse而不是Convert.ToInt32,因为用户输入不一定是有效的整数 然后我们可以使用它:Java while循环中的扫描仪,java,c#,if-statement,while-loop,Java,C#,If Statement,While Loop,我可以在C中使用什么?没有扫描仪 这篇文章没有解释如何用C语言制作扫描仪。它只解释了如何解析用户的输入,使其仅为整数。让我们为它提取一个ReadInteger方法。请注意,我们使用int.TryParse而不是Convert.ToInt32,因为用户输入不一定是有效的整数 然后我们可以使用它: private static int ReadInteger(String title = null) { if (!string.IsNullOrWhiteSpace(title))
private static int ReadInteger(String title = null)
{
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
while (true)
{
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Sorry, the input is not a valid integer, try again");
}
}
Convert.ToInt32会根据用户输入的内容引发异常。Int32.TryParse是一个更好的选择。如果您真的需要类似Java的扫描仪,您可以移植。C转换应该非常简单。谢谢。这是我一直在努力解决的一个部分:如果int.tryparseconole.ReadLine,out int result返回结果@喂机器:我明白了;与c不同,Java没有ref和out参数
int x;
x = scn.nextInt();
private static int ReadInteger(String title = null)
{
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
while (true)
{
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Sorry, the input is not a valid integer, try again");
}
}
public void Play()
{
while (true)
{
// We should re-read value after each attempt
int value = ReadInteger();
if (value > theNumber)
{
Console.WriteLine("your number is too big");
}
else if (value < theNumber)
{
Console.WriteLine("your number is too big");
}
else
{
Console.WriteLine("you got it");
break;
}
}
}