2017-08-25 10 views
0

該解決方案旨在讀取包含由三行組成的記錄的文本文件。記錄的第一行是合格的測試值,第二行是問題,第三行是答案。C#試圖讀取文件到數組並隨機選擇基於整數測試的行

執行時,它會檢查是否只有一條記錄或是否有多條記錄。

問題是當有多個記錄時:
它是爲了隨機選擇記錄數量範圍內的數字來決定記錄。一旦它決定了該記錄,那麼該程序就是要查看它生成的隨機值是否在通過測試值的範圍內,與通過的測試值相匹配以批准該記錄。所有這些都是爲了在一個while循環中運行,直到選擇一條記錄爲止,隨機值作爲記錄的通過測試值傳遞。

我相信它應該可以工作,但是當我啓動程序時,它似乎處於無限循環中,因爲當只有兩個記錄時或者傳遞值爲兩個時。

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.IO; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace WindowsFormsApp1 
{ 
    public partial class Quiz : Form 
    { 
     Random rnd = new Random(0); 
     public Quiz() 
     { 
      InitializeComponent(); 
      checkFile(); 
      quizInit();    

     } 

     void checkFile() 
     { 
      if (File.Exists("quiz.txt")) 
       MessageBox.Show("Quiz File Exists"); 
      else 
      { 
       StreamWriter quizFile = new StreamWriter("quiz.txt"); 
       quizFile.Close(); 
      } 
     } 

     void quizInit() 
     { 
      string[] quiz = File.ReadAllLines("quiz.txt"); 
      string question = ""; 
      string answear = ""; 
      int lineCount = quiz.Length; 
      if (lineCount == 3) 
      { 
       question = quiz[lineCount - 2]; 
       answear = quiz[lineCount - 1]; 
       qLbl.Text = question; 
       aLbl.Text = answear; 
      } 
      if (lineCount > 3) 
      { 

       bool approved = false; 
       int choises = lineCount/3; 
       int selection = 0; 
       int check = 0; 
       while(approved == false) 
       { 
        selection = rnd.Next(1, 2); 
        check = Convert.ToInt32(quiz[selection * 3 - 3]); 
        if(rnd.Next(1,check) == check) approved = true; 
       } 
       qLbl.Text = quiz[selection * 3 - 2]; 
       aLbl.Text = quiz[selection * 3 - 1]; 
       check++; 
       quiz[selection * 3 - 3] = check.ToString(); 
       File.WriteAllLines("quiz.txt", quiz); 
      } 
     } 

     private void newEntryBtn_Click(object sender, EventArgs e) 
     { 
      if (string.IsNullOrWhiteSpace(qTxtbx.Text) && 
       string.IsNullOrWhiteSpace(aTxtbx.Text)) MessageBox.Show("Fill Both Boxes!"); 
      else 
      { 
       StreamWriter quizFile = new StreamWriter("quiz.txt", true); 
       quizFile.WriteLine((1).ToString()); 
       quizFile.WriteLine(qTxtbx.Text); 
       quizFile.WriteLine(aTxtbx.Text); 
       quizFile.Close(); 
      } 
      quizInit(); 

     } 

     private void newBtn_Click(object sender, EventArgs e) 
     { 
      quizInit(); 
     } 
    } 
} 

這是輸入:

2 
q 
a 
1 
q1 
a1 
+0

如果輸入未知,我們如何檢查您的代碼? –

+0

剛剛添加了輸入 –

回答