我希望用户从键盘按键,然后希望计算机判断键是字母,符号还是数字。 [英] I want the user to press a key from keyboard and then want the computer to tell if the key is a alphabet, symbol or a number.
问题描述
我希望用户从键盘按键,并希望计算机判断键是字母,符号还是数字。但是代码中存在一些错误。你能指出吗?
I want the user to press a key from keyboard and want the computer to tell if the key is a alphabet, symbol or a number. But some error is there in the code. Can you point out ?
Console.WriteLine("type a character");
int character = int.Parse(Console.ReadLine());
string type = " ";
if ((character>=48) && (character<=57))
{
type = "integer";
}
else if ((character >= 65) && (character <= 90))
{
type = "uppercase alphabet";
}
else if ((character >= 97) && (character <= 122))
{
type = "lowecase character";
}
else
{
type = "symbol";
}
Console.WriteLine("the type of character that you have entered is " +type);
Console.ReadLine();
推荐答案
问题是当用户键入一个键时,你试图解析它到int:
The problem is that when the user types a key, you try to parse it to an int:
int character = int.Parse(Console.ReadLine());
这意味着从数字1234的字符串表示转换为可以数学处理的整数版本。
因此,如果用户输入8,int.Parse将返回值8 - 小于48,因此它将使所有测试失败。
而是直接使用该字符:
Which means convert from a string representation of a number "1234" to an integer version that can be handle mathematically.
So if the user types an "8" for example, int.Parse will return the value 8 - which is less than 48, so it will fail all your tests.
Instead, use the character directly:
string userInput = Console.ReadLine();
foreach (char c in userInput)
{
string type = "unknown";
if (c >= '0' && c <= '9')
{
type = "integer";
}
else if ...
或者更好,使用内置函数:
Or better, use the built in functions:
string userInput = Console.ReadLine();
foreach (char c in userInput)
{
string type = "symbol";
if (char.IsDigit(c))
{
type = "integer";
}
else if (char.IsLetter(c))
{
if (char.IsLower(c))
{
type = "lowercase character";
}
else
{
type = "uppercase character";
}
}
...
}
这篇关于我希望用户从键盘按键,然后希望计算机判断键是字母,符号还是数字。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!