Console.Read没有返回我的int32
我不明白为什么我的整数没有正确出来,Console.Read()方法说它返回一个整数,为什么WriteLine没有正确显示它?
int dimension; dimension = Console.Read(); Console.WriteLine(""+ dimension);
Console.Read()
仅返回键入内容的第一个字符。 您应该使用Console.ReadLine()
:
例:
int suppliedInt; Console.WriteLine("Please enter a number greater than zero"); Int32.TryParse(Console.ReadLine(), out suppliedInt); if (suppliedInt > 0) { Console.WriteLine("You entered: " + suppliedInt); } else { Console.WriteLine("You entered an invalid number. Press any key to exit"); } Console.ReadLine();
其他资源:
MSDN – Console.Read()
MSDN – Console.ReadLine()
来自MSDN :
回报价值
类型:System.Int32输入流中的下一个字符,如果当前不再有要读取的字符,则为负一(-1)。
你的程序正在返回,但你没有看到,请问下面的代码块:
如果输出窗口没有停留,您将无法看到输出。
int dimension; dimension = Console.Read(); Console.WriteLine("" + dimension); Console.ReadLine();
Console.Read()返回输入中第一个符号的ASCII码。 你可以做
int dimension; dimension = Console.Read(); Console.WriteLine(""+ (char)dimension);
你会在输入中看到正确的第一个符号,如
(char)dimension
将通过它的ASCII码给你符号。
int a = 0; if(Int32.TryParse(Console.ReadLine(), out a)) { // Do your calculations with 'a' } else { // Some warnings }
Console.Read
方法只返回一个包含在int
的单个字符,因此仅当您读取的数字只有一位数时才适用,否则您将始终只获得第一个数字。
由于Read
的返回值实际上是一个字符,因此不能直接将其用作整数,您需要将其从字符解析为整数。
但假设您想要一个长于一位数的数字,那么您确实需要使用Console.ReadLine
并使用int.TryParse
将输入转换为整数。 如果int.TryParse
返回false
您可以警告用户他提供了无效输入并再次请求维度。
示例代码:
int维;
bool isValidDimension; do { Console.Write("Dimension: "); string input = Console.ReadLine(); isValidDimension = int.TryParse(input, out dimension); if (!isValidDimension) { Console.WriteLine("Invalid dimension... please try again."); Console.WriteLine(); } } while (!isValidDimension);
你应该如下
static void Main() { int Number; string strNumber; strNumber = Console.ReadLine(); Number = int.Parse(strNumber); Console.WriteLine("" + dimension); }