比较字符串长度和字符串值之间的区别

时间:2013-02-23 12:29:00

标签: c# string if-statement console-application

namespace ProgrammingTesting
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter the input");

            string input1 = Console.ReadLine();
            if (input1 == "4")
            {
                Console.WriteLine("You are a winnere");
                Console.ReadLine();
            }
            else if (input1.Length < 4)
            {
                Console.WriteLine("TOOOOO high");

            }
            else if (input1.Length > 4)
            {
                Console.WriteLine("TOOOO Low");
                                Console.ReadLine();
            }       
        }
    }
}

如果输入的数字小于4,为什么程序输出“太低”。

2 个答案:

答案 0 :(得分:5)

您没有比较您要比较输入长度的值。您还需要将字符串的输入转换为整数。例如:

if (int.Parse(input1) < 4) {
    ...
}

答案 1 :(得分:1)

input1是一个字符串。

input1.Length是字符串的长度。

您希望在比较之前将字符串转换为数字值。

你还需要看一下你的方向,而不是方向。

Console.WriteLine("Please enter the input");

string input1 = Console.ReadLine();
int number;
bool valid = int.TryParse(out number);

if (! valid)
{
    Console.WriteLine("Entered value is not a number");
}
else
{

    if (number == 4)
    {
        Console.WriteLine("You are a winnere");
    }
    else if (number > 4)
    {
        Console.WriteLine("TOOOOO high");
    }
    else if (number < 4)
    {
        Console.WriteLine("TOOOO Low");
    }
}

Console.ReadLine();
相关问题