這一講是關於文件及流的操作。我們來做一個綜合但不太復雜的程序"背單詞"。
要求如下:
(4分)能將英語四級單詞文本文件的內容讀出來及放到內存的數組或列表中(使用StreamReader的循環讀ReadLine()或直接ReadToEnd(), 然后用string的Split('\n')分割成多行;然后對每一行Trim().Split('\t')得到的string[]的第0個即為英語單詞,第1個即為漢語意思,可以放到兩個數組或列表List中)。
(4分)使用大仕老師最喜歡的Timer,每隔一定時間,讓英語單詞及漢語意思顯示到屏幕上(可以用兩個標簽控件)。(注意要有一個下標變量,每次加加,以實現每次顯示的單詞不同)。(再提示:讓窗體的TopMost屬性置為True,這個窗體就不會被其他窗口遮蓋,你就可以隨時隨地背單詞了!)
(2分)你可以加點花樣,如隨機,如可以讓用戶可以調整背單詞的速度,或者你可以將界面做得比較cool,更高級的是還可以保存進度,再高級的是使用艾賓浩斯遺忘曲線(我們的作業要求不要這么高,再高就是一個商業軟件的的要求了,呵呵)。
運行結果:
代碼如下:
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 WindowsFormsApp4 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } int t1 = 0; private void timer1_Tick(object sender, EventArgs e) { #region 從文件讀取數據 List<string> english = new List<string>(); List<string> chinese = new List<string>(); StreamReader sw = new StreamReader("F:\\College_Grade4.txt", Encoding.Default); string content = sw.ReadToEnd(); string[] lines = content.Split('\n'); for (int i = 0; i < lines.Length; i++) { string[] words = lines[i].Trim().Split('\t'); if (words.Length < 2) continue; english.Add(words[0]); chinese.Add(words[1]); } if (t1 < lines.Length) { this.label1.Text = english[t1]; this.label2.Text = chinese[t1]; } t1++; this.label6.Text = t1.ToString(); #endregion } private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { int i = Convert.ToInt32(this.textBox1.Text); this.timer1.Interval = i; } } }
參考資料:
https://blog.csdn.net/u011367578/article/details/82951985?utm_source=blogxgwz0