2014-11-09 81 views
-1

我正在研究基本控制檯程序,如下所示。我很煩惱,後面這段代碼不起作用。什麼是檢查用戶輸入年齡並從Console.WriteLine重新運行代碼的最佳方法(「好吧,現在請輸入您的年齡。」);到if語句。與此根據條件重新運行代碼塊

int newAge = Convert.ToInt32(age); 

int newAge = Int32.Parse(age); 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace Practice 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Console.WriteLine("Thank you for participating in this survey. Please take a moment to fill out the required information."); 
      Console.WriteLine("Please Type Your Name"); 

      string name = Console.ReadLine(); 

      Console.WriteLine("Okay. Now please enter your age."); 

      string age = Console.ReadLine(); 

      Console.WriteLine("Your information has been submitted."); 

      Console.WriteLine("Name: " + name + "\n" + "Age: " + age); 

      Console.ReadLine(); 

      int newAge = Int32.Parse(age); 

      if (newAge => 18) 
      { 

      } 

     } 
    } 
} 
+2

你似乎已經知道如何字符串轉換成int。請修正您的標題,以便正確反映您正在尋求幫助的內容。請參閱http://stackoverflow.com/help/how-to-ask – 2014-11-09 00:59:34

回答

0

你也可以使用的TryParse,這確實錯誤測試你,並返回分析得到的值作爲out參數。由於TryParse返回一個布爾值,你可以很容易地檢查轉換是否工作。

string age = null; 
int ageValue = 0; 
bool succeeded = false; 

while (!succeeded) 
{ 
    Console.WriteLine("Okay, now input your age:"); 
    age = Console.ReadLine(); 
    succeeded = int.TryParse(age, out ageValue); 
} 

你也可以顛倒它做的......而

string age = null; 
int ageValue = 0; 
do 
{ 
    Console.WriteLine("Okay, now input your age:"); 
    age = Console.ReadLine(); 
} while (!int.TryParse(age, out ageValue)); 
+0

謝謝你的幫助。結果很好。 – Mbdelta 2014-11-09 01:16:32

0

替換此。 ,如果你想更好的代碼使用的try-catch

try 
{ 
int newAge = Convert.ToInt32(age); 
} 
catch(FormatException) 
{ 
//do something 
} 
+0

我仍然有我的if語句發出錯誤的問題http://prntscr.com/54gmwf – Mbdelta 2014-11-09 01:05:46

+0

您應該使用'> ='而不是'=>' – Tico 2014-11-09 01:07:42

+0

啊,謝謝你,這工作。 – Mbdelta 2014-11-09 01:15:39