2013-02-23 114 views
0
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,爲什麼程序不輸出「太低」。比較字符串長度和字符串值之間的區別

+3

類型'12345'看到'Tooo Low' – I4V 2013-02-23 12:30:23

+0

你想測試輸入的字符串的長度,或輸入數字的數值? – nnnnnn 2013-02-23 12:31:55

+0

你想做什麼?少於4個符號或少於輸入4? – 2013-02-23 12:32:34

回答

5

您沒有比較您比較輸入長度的值。您還需要將來自字符串的輸入轉換爲整數。例如:

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

對於控制檯應用程序,我發現最好使用'TryParse'和while循環。因此用戶輸入被正確驗證並以用戶友好的方式進行驗證。 – Leri 2013-02-23 12:33:47

+1

@PLB當然,我傾向於使用'TryParse',這只是一個簡單的例子。 – Lloyd 2013-02-23 12:37:57

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();