我的任务是编写一个程序,该程序访问包含篮球运动员姓名和得分的外部文本文件。无论语言如何,我总是在从 txt 文件读取和写入时遇到问题。从txt文件读取后,程序应该输出所有玩家的平均分数以及最高得分者的玩家姓名。这是我所拥有的:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace TextFiles
{
public partial class BasketBallStats : Form
{
List<int> marks = new List<int>();
public BasketBallStats()
{
InitializeComponent();
}
// Form load event handler used to construct
// object of the Streamwriter class, sending the
// new filename as an argument. Enclosed in
// try...catch block.
public class BasketballController
{
public class Entry
{
public int Value { get; set; }
public string Name { get; set; }
}
BasketballController(string filename)
{
this.filename = filename;
}
private string filename;
private List<Entry> data = new List<Entry>();
public List<Entry> Data
{
get
{
// Clear data
data.Clear();
// Iterate through lines
foreach (string line in System.IO.File.ReadLines(filename))
{
// Split by space
List<string> parts = line.Trim().Split(' ').ToList();
if (parts.Count() < 2)
continue;
// Number is last space separated string
int number = int.Parse(parts.Last());
// Remove number
parts.RemoveAt(parts.Count() - 1);
// Name is any previous word joined by space
string name = string.Join(" ", parts).Trim();
// Add number and name to data
data.Add(new Entry() { Name = name, Value = number });
}
// Sort from greater value to smaller
data.Sort(Comparer<Entry>.Create(
(l, r) => r.Value.CompareTo(l.Value)));
return data;
}
set
{
using (var writer = new System.IO.StreamWriter(filename))
{
foreach (var entry in value)
{
writer.WriteLine(string.Format("{0} {1}", entry.Name, entry.Value));
}
}
data = value;
}
}
public double Average
{
get
{
// Read file if data is empty, otherwise reuse its value
var src = (data.Count() == 0) ? Data : data;
if (src.Count() == 0)
return 0.0;
// Return average
return src.Average(x => x.Value);
}
}
}
private string score;
public List<int> Marks { get => Marks1; set => Marks1 = value; }
public List<int> Marks1 { get => marks; set => marks = value; }
private void BasketBallStats_Load(object sender, EventArgs e)
{
}
private void BtnCreateFile_Click(object sender, EventArgs e)
{
score = "basketBallScore.txt";
if (File.Exists(score))
{
Console.WriteLine("FileName: {0}", score);
Console.WriteLine("Attributes: {0}",
File.GetAttributes(score));
Console.WriteLine("Created: {0}",
File.GetCreationTime(score));
Console.WriteLine("Last Accessed: {0}",
File.GetLastAccessTime(score));
DirectoryInfo dir = new DirectoryInfo(".");
Console.WriteLine("Current Directory: n{0} n",
Directory.GetCurrentDirectory());
Console.WriteLine("File Name".PadRight(52) +
"Size".PadRight(10) + "Creation Time");
foreach (FileInfo fil in dir.GetFiles("*.*"))
{
string name = fil.Name;
long size = fil.Length;
DateTime creationTime = fil.CreationTime;
Console.WriteLine("{0} {1,12:NO} {2, 20:g} ", name.PadRight(45),
size, creationTime);
}
}
else
{
Console.WriteLine("{0} not found - using current" +
"directory:", score);
}
Console.ReadKey();
}
private void BtnWriteFile_Click(object sender, EventArgs e)
{
try
{
var WriteToFile = new System.IO.StreamWriter("basketBallScore.txt"); //create textfile in default directory
WriteToFile.Write(listView1.Text + ", " + listView1.Text + ", " + listView1.Text + ", " + listView1.Text);
WriteToFile.Close();
Marks.Add(Convert.ToInt32(listView1.Text)); //add to list
}
catch (System.IO.DirectoryNotFoundException)
{
lblMessage.Text = "File did not close properly: "; //add error message
}
}
private void ManipulateFile_Click(object sender, EventArgs e)
{
int[] hoursArray = new int[30];
StreamReader fileSR = new StreamReader("basketBallScore.txt");
int counter = 0;
string line = "";
line = fileSR.ReadLine();
while (line != null)
{
hoursArray[counter] = int.Parse(line);
counter = counter + 1;
line = fileSR.ReadLine();
}
fileSR.Close();
int total = 0;
double average = 0;
for (int index = 0; index < hoursArray.Length; index++)
{
total = total + hoursArray[index];
}
average = (double)total / hoursArray.Length;
int high = hoursArray[0];
for (int index = 1; index < hoursArray.Length; index++)
{
if (hoursArray[index] > high)
{
high = hoursArray[index];
}
}
Console.WriteLine("Highest number is: " + high);
Console.WriteLine("The average is: " + average);
Console.ReadLine();
}
private void BasketBallStats_Load_1(object sender, EventArgs e)
{
}
private void CalcAverage_Click(object sender, EventArgs e)
{
int totalmarks = 0;
foreach (int m in Marks)
totalmarks += m;
MessageBox.Show("Average Is: " + totalmarks / Marks.Count);
}
private void Button1_Click(object sender, EventArgs e)
{
var c = new BasketballController("basketBallScore.txt");
Debug.WriteLine(string.Format("Average {0}", c.Average));
Debug.WriteLine(string.Format("First {0} {1}", c.Data.First().Name, c.Data.First().Value));
Debug.WriteLine(string.Format("Last {0} {1}", c.Data.Last().Name, c.Data.Last().Value));
}
}
}
这是文本文件包含的内容:
Lebron James 31
Steph Curry 12
Kyrie Irving 37
Kevin Durant 9
Paul George 35
Klay Thompson 8
J.R.Smith 12
Zaza Pachulia 4
Tristan Thompson 10
Draymond Green 2
程序将访问该文件,但除了验证数据文件之外,不会提供任何输出。
几件事:
- 当您在代码中看到文件名两次(实际上是 4 次(时,您遇到了等待发生的问题。将所有这些文本替换为类成员。
- 通常在处理文本文件时,您不会使它们保持打开状态,而是遵循以下模式:
- 以只读模式打开文件
- 读取数据
- 关闭文件
- 对数据执行某些操作
- 在写入模式下打开文件
- 写入数据(覆盖以前的文件(
- 关闭文件 并在打开和关闭操作之间尽可能少地等待。无论你如何制作它们。
代码的主要问题是表单何时加载:
private void Form1_Load(object seneder, EventArgs e)
{
try
{
filbasketBallStat = new StreamWriter("basketBallScore.txt");
如果您检查 StreamWriter(字符串( 构造函数的 MSDN,您将阅读以下内容:
因此,当运行此文件时,您的文件最终应该是空白的,因此没有什么可阅读的,也没有什么可报告的。如果该文件存在,则会覆盖该文件;否则,将创建一个新文件。
您可能还应该将功能从表单中抽象出来。这将为您提供更大的灵活性,并允许您更轻松地进行调试。
这应该有效:
class BasketballController
{
public class Entry
{
public int Value { get; set; }
public string Name { get; set; }
}
BasketballController(string filename)
{
this.filename = filename;
}
private string filename;
private List<Entry> data = new List<Entry>();
public List<Entry> Data
{
get
{
// Clear data
data.Clear();
// Iterate through lines
foreach (string line in System.IO.File.ReadLines(filename))
{
// Split by space
List<string> parts = line.Trim().Split(' ').ToList();
if (parts.Count() < 2)
continue;
// Number is last space separated string
int number = int.Parse(parts.Last());
// Remove number
parts.RemoveAt(parts.Count() - 1);
// Name is any previous word joined by space
string name = string.Join(" ", parts).Trim();
// Add number and name to data
data.Add(new Entry() { Name = name, Value = number });
}
// Sort from greater value to smaller
data.Sort(Comparer<Entry>.Create(
(l, r) => r.Value.CompareTo(l.Value)));
return data;
}
set
{
using (var writer = new System.IO.StreamWriter(filename))
{
foreach (var entry in value)
{
writer.WriteLine(string.Format("{0} {1}", entry.Name, entry.Value));
}
}
data = value;
}
}
public double Average
{
get
{
// Read file if data is empty, otherwise reuse its value
var src = (data.Count() == 0) ? Data : data;
if (src.Count() == 0)
return 0.0;
// Return average
return src.Average(x => x.Value);
}
}
}
请注意任何文件处理代码是如何组合在一起的,以及它在尽快打开后是如何关闭的。
您可以像这样使用该类:
var c = new BasketballController("basketBallScore.txt");
Debug.WriteLine(string.Format("Average {0}", c.Average));
Debug.WriteLine(string.Format("First {0} {1}", c.Data.First().Name, c.Data.First().Value));
Debug.WriteLine(string.Format("Last {0} {1}", c.Data.Last().Name, c.Data.Last().Value));
哪些输出:
Average 16
First Kyrie Irving 37
Last Draymond Green 2
尝试以下代码来读取文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:temptest.txt";
static void Main(string[] args)
{
new Player(FILENAME);
}
}
public class Player
{
const int NAME_COL_WIDTH = 20;
public static List<Player> players = new List<Player>();
public string name { get; set; }
public int score { get; set; }
public Player() { } //player constructor with no parameters
public Player(string filename)
{
StreamReader reader = new StreamReader(filename);
string inputLine = "";
while((inputLine = reader.ReadLine()) != null)
{
Player newPlayer = new Player();
players.Add(newPlayer);
newPlayer.name = inputLine.Substring(0, NAME_COL_WIDTH).Trim();
newPlayer.score = int.Parse(inputLine.Substring(NAME_COL_WIDTH));
}
reader.Close();
}
}
}