我的代码出现以下错误
Program.Main(string[]) 并非所有代码路径都返回值
我试图理解它的确切含义,但无济于事。该代码旨在导入一个.txt充满整数的文件,然后按升序对它们进行排序。它还没有完全完成,但这是我一段时间以来最接近的:
static object Main(string[] args)
{
//take file
Console.Write("Please select file: ");
//take filename/path
string select = Console.ReadLine();
Console.Write("File " + select + " Selected, Press any key.");
Console.ReadLine();
//take contents
string[] thefile = File.ReadAllLines(select);
//generate array size
int a = 0;
foreach (string Line in thefile)
{
a++;
}
//make the list
List<int> thelist = new List<int>();
//current value in list to display
int b = 0;
foreach (string Line in thefile)
{
int current = Convert.ToInt32(thelist[b]);
thelist.Add(current);
thelist.Sort();
Console.WriteLine(thelist[b]);
b++;
}
}
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个错误?
改变
static object Main(string[] args)
到
static void Main(string[] args)
您的定义是说该Main方法将返回object,但return我没有看到任何语句。
最重要的事情正在发生变化object来void。object意味着该Main()方法需要在return某处声明。void意味着它不必有一个。进行此更改,代码至少会编译。
这一行还有一个问题:
int current = Convert.ToInt32(thelist[b]);
Run Code Online (Sandbox Code Playgroud)
因为thelist[b]尚未分配任何内容。你想要这个:
int current = Convert.ToInt32(Line);
Run Code Online (Sandbox Code Playgroud)
现在代码应该几乎可以产生良好的输出。您还需要将Sort()和移动WriteLine()到一个单独的循环中,该循环在插入所有整数后运行。否则,现有的循环只是输出在每次迭代当前最大的项目,也是这样慢于它需要的,因为它重新排序各一次。
最后,整个循环填充a变量只是额外浪费的代码和 CPU。您可以从 获取此值theFile.Length,但您不需要,因为它从未使用过。
像这样把它们放在一起:
static void Main(string[] args)
{
//take file
Console.Write("Please select file: ");
string select = Console.ReadLine();
Console.Write("File " + select + " Selected, Press any key.");
Console.ReadLine();
//take contents
string[] thefile = File.ReadAllLines(select);
List<int> thelist = new List<int>();
foreach (string Line in thefile)
{
int current = Convert.ToInt32(Line);
thelist.Add(current);
}
//write contents
theList.Sort();
foreach(int number in thelist)
{
Console.WriteLine(number);
}
}
Run Code Online (Sandbox Code Playgroud)
我想你可能还想看看使用更新的语言功能有什么可能:
static void Main(string[] args)
{
Console.Write("Please enter a file name: ");
string fileName = Console.ReadLine();
Console.Write($"File {fileName} selected. Press any key.");
Console.ReadKey(true);
var numbers = File.ReadLines(fileName).Select(line => int.Parse(line)).OrderBy(i => i);
foreach(int number in numbers)
{
Console.WriteLine(number);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
85 次 |
| 最近记录: |