【发布时间】:2018-11-20 17:42:16
【问题描述】:
我正在尝试创建一个程序来计算文件中的 ASCII 字符并跟踪每个字符在文件中出现的次数。然后它应该将输出写入文件。如果文件只是读取“Hello”,则输出文件应格式化为显示:
H(72) 1 e(101) 1 升(108) 2 o(111) 1 .(46) 1
目前我写的代码如下:
using System.IO;
using System;
using System.Collections;
class CharacterFrequency
{
char ch;
int frequency;
public char getCharacter()
{
return ch;
}
public void setCharacter(char ch)
{
this.ch = ch;
}
public int getfrequency()
{
return frequency;
}
public void setfrequency(int frequency)
{
this.frequency = frequency;
}
static void Main()
{
string OutputFileName;
string InputFileName;
Console.WriteLine("Enter the file path");
InputFileName = Console.ReadLine();
Console.WriteLine("Enter the outputfile name");
OutputFileName = Console.ReadLine();
StreamWriter streamWriter = new StreamWriter(OutputFileName);
string data = File.ReadAllText(InputFileName);
ArrayList al = new ArrayList();
al.Add(data);
//create two for loops to traverse through the arraylist and compare
for (int i = 0; i < al.Count; i++)
{
//create variable k to count the repeated element
//(if k>0 it means that the particular element is not the first instance)
int k = 0;
//count frequency variable
int f = 0;
for (int j = 0; j < al.Count; j++)
{
//compare the characters
if (al[i].Equals(al[j]))
{
f++;
if (i > j) { k++; }
}
}
if (k == 0)
{
//Display in the correct format
Console.Write(al[i] + "(" + (int)al[i] + ")" + f + " ");
}
}
}
}
我在最后一行代码 (Console.Write) 上收到错误消息:“指定的转换无效。”我知道这个程序可能写得不正确,但我很难用数组列表来完成这个任务。我已经在之前的程序中使用排序字典完成了这项任务,但现在我必须使用数组列表。非常感谢有关如何修复错误以及我的程序外观的任何建议。
【问题讨论】:
-
你为什么使用ArrayList?请改用
List<T> -
您不能以这种方式将 char 转换为 int。尝试改用 GetNumericValue。
-
您甚至不需要这样做,只需从修复错误的 Console.WriteLine() 中删除“(int)”,但您仍然必须完成编写代码以计算字符
标签: c# arraylist casting char ascii