这一讲是关于文件及流的操作。我们来做一个综合但不太复杂的程序"背单词"。
要求如下:
(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