2017-09-14 73 views
-2
private void btn_Save_Click(object sender, EventArgs e) 
    { 
     // Declare int variable. 
     int randomNumber = 0; 

     // Declare a StreamWriter variable. 
     StreamWriter outputFile; 

     // Get the number of random integers to hold in file. 
     int number = int.Parse(txt_Number.Text); 

     if (saveFile.ShowDialog() == DialogResult.OK) 
     { 
      // Create the selected file. 
      outputFile = File.CreateText(saveFile.FileName); 

      // Create a Random Object. 
      Random Rand = new Random(); 

      for (int count = 0; count < number; count++) 
      { 
       // Get random integers and assign them to randomNumber. 
       randomNumber = Rand.Next(1, 101); 

       // Write data to the file. 
       outputFile.WriteLine(randomNumber); 

       // Close the file. 
       outputFile.Close(); 

       MessageBox.Show("File saved in path:" + saveFile.FileName); 
      } 
     } 
     else 
     { 
      // Display an error message. 
      MessageBox.Show("Operation Cancelled"); 
     } 
    } 

    private void btn_Clear_Click(object sender, EventArgs e) 
    { 
     // Clear the TextBox. 
     txt_Number.Text = ""; 
    } 

    private void btn_Exit_Click(object sender, EventArgs e) 
    { 
     // Close the form. 
     this.Close(); 
    } 
} 

問題是:創建一個程序,將一系列隨機數寫入文件。每個隨機數應該在1到100的範圍內。應用程序應讓用戶指定文件將保存多少個隨機數。Visual C#隨機數文件編寫器

該代碼正在工作,但我有輸出writeline問題。 每次我運行程序時,它都會說未處理的異常,並且無法寫入Closed TextWriter。 而不是保存多個隨機數,它只保存一個。 有關這兩個問題的任何幫助都會很好。

+3

錯誤的哪部分你不明白?您的代碼在關閉後嘗試寫入文件。 – SLaks

+3

在寫入文件的循環前面放置一個斷點。運行你的程序,用F10鍵逐行執行代碼。密切關注 - 非常非常密切的注意力集中在你看到你的代碼所做的每件事情上。你會開悟的。我無法承諾宇宙意識,但你至少會讓你的代碼工作。 –

+3

@EdPlunkett:嘿,我也在其他問題上使用這種方法。你認爲這是解決問題的通用方法嗎? –

回答

-2

你的錯誤是在這裏爲循環:

for (int count = 0; count < number; count++) 
     { 
      // Get random integers and assign them to randomNumber. 
      randomNumber = Rand.Next(1, 101); 

      // Write data to the file. 
      outputFile.WriteLine(randomNumber); 

      // Close the file. 
      outputFile.Close(); 

      MessageBox.Show("File saved in path:" + saveFile.FileName); 
     } 

您可以通過所有的數字迭代之前關閉該文件。因此,你不能寫出第一個數字。關閉功能應該在for循環之外,如下所示:

for (int count = 0; count < number; count++) 
     { 
      // Get random integers and assign them to randomNumber. 
      randomNumber = Rand.Next(1, 101); 

      // Write data to the file. 
      outputFile.WriteLine(randomNumber); 

      MessageBox.Show("File saved in path:" + saveFile.FileName); 
     } 


     // Close the file outside for loop 
     outputFile.Close(); 
+0

謝謝。我其實並沒有意識到這個錯誤 –

+0

你不應該直接推薦使用'Close'。你應該推薦正確調用'Close'和'Dispose'的'using'語句 –