2016-08-03 147 views
-1

我有一個簡單的控制檯應用程序,我希望使用者只能輸入數字。這裏的代碼如何在控制檯應用程序中輸入數字c#

namespace ConsoleApplication3 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
     int n, sum; 
     sum = 5000; 
     Console.WriteLine("enter number of conversations"); 
     n = int.Parse(Console.ReadLine()); 
     if (n <= 100) 
     { 
      sum = sum + n * 5; 
     } 
     else 
     { 
      sum += (100 * 5) + (n - 100) * 7; 
     } 
     Console.WriteLine(sum); 
     Console.ReadKey(); 
     } 
    } 
} 
+1

那麼問題是什麼? – Idos

回答

2

這應該做的伎倆。在這種情況下,你

Console.Write("enter number of conversations "); 
int n; 

while(!int.TryParse(Console.ReadLine(), out n) 
{ 
    Console.Clear(); 
    Console.WriteLine("You entered an invalid number"); 
    Console.Write("enter number of conversations "); 
} 

if(n <= 100) 
    //continue here 
2

投注選項int.TryParse而不是爲int.Parse()它可以幫助你確定無效輸入。你可以實現以下邏輯來使其工作;

Console.WriteLine("enter number of conversations"); 
if(int.TryParse(Console.ReadLine(), out n) 
{ 
    if (n <= 100) 
    { 
     sum = sum + n * 5; 
    } 
    else 
    { 
     sum += (100 * 5) + (n - 100) * 7; 
    } 
    Console.WriteLine(sum); 
} 
else 
{ 
    Console.WriteLine("Invalid input , Enter only number"); 
} 
1

您應該使用,而不是「解析」和使用「的TryParse」梅索德一個「做{...} while」循環,這樣你就不必再重複醜陋的代碼。

注意我已經添加了一個字符串變量來處理用戶輸入。此代碼會一次又一次地詢問轉換次數,直到輸入有效數字。然後它會執行你的其他代碼。

class Program 
{ 
    static void Main(string[] args) 
    { 
     int n, sum; 
     string input; 
     sum = 5000; 

     do 
     { 
      Console.WriteLine("enter number of conversations"); 
      input = Console.ReadLine(); 
     } while (int.TryParse(input, out n) == false); 

     if (n <= 100) 
     { 
      sum = sum + n * 5; 
     } 
     else 
     { 
      sum += (100 * 5) + (n - 100) * 7; 
     } 
     Console.WriteLine(sum); 
     Console.ReadKey(); 
    } 
} 
相關問題