2016-06-13 16 views
0

當我運行它跳過第一個readline並重復第一個「for」無限次
起初,它給了我nullreferenceexception錯誤,這就是當我添加第一行首先爲
我是新來的編碼所以請讓該解決方案是簡單跳過readline並重復無限次與數組c#

這是代碼:使用Console.Read()Console.ReadLine()

class People 
{ 
    public string name; 
    public string address; 
    public int age; 


    public void setvalues(string na, string ad, int ag) 
    { 
     this.name = na; 
     this.address = ad; 
     this.age = ag; 
    } 
} 
class Program 
{ 
    static void Main(string[] args) 
    { 
     Console.Write("Enter the number of People you want to add : "); 
     int q = Convert.ToInt32(Console.Read()); 

     People[] plist = new People[q]; 
     string[] namelist = new string[q]; 
     string[] addresslist = new string[q]; 
     int[] agelist = new int[q]; 


     for (int i = 0; i < q; i++) 
     { 
      plist[i] = new People(); 
      Console.WriteLine("Enter the name of the person :  "); 
      namelist[i] = Console.ReadLine(); 
      Console.Write("Enter the address of the person : "); 
      addresslist [i] = Console.ReadLine(); 
      Console.Write("Enter the age of the person : "); 
      agelist[i] =Convert.ToInt32(Console.ReadLine()); 
     } 
     for (int s = 0; s < q; s++) 
     { 
      plist[s].setvalues (namelist[s], addresslist[s], agelist[s]); 
     } 
    } 
    } 
} 

回答

0

你需要照顧。

Read()只讀取第一個可用字符。所有其他(可用)字符都保留在輸入緩衝區中。

ReadLine()直到找到行尾字符(通常爲\n)。

因此,當用戶對q輸入值和命中輸入Read()只讀取第一個字符,但輸入已經存儲在緩衝區中。這個輸入然後在ReadLine()讀取,然後用戶有機會輸入該行的適當值。

我認爲你最好的選擇是用ReadLine()替換你的第一個Read()

+0

感謝您的有用和真正的快速答覆。 –