C# 不是所有的行都返回一个值,我不确定该怎么做
我的代码出现以下错误 Program.Mainstring[]并非所有代码路径都返回值 我试图理解它的确切含义,但没有用。该代码旨在导入一个充满整数的.txt文件,然后按升序对其进行排序。它还没有完全完成,但这是我一段时间以来最接近的一次:C# 不是所有的行都返回一个值,我不确定该怎么做,c#,C#,我的代码出现以下错误 Program.Mainstring[]并非所有代码路径都返回值 我试图理解它的确切含义,但没有用。该代码旨在导入一个充满整数的.txt文件,然后按升序对其进行排序。它还没有完全完成,但这是我一段时间以来最接近的一次: static object Main(string[] args) { //take file Console.Write("Please select file: "); //take filename/path strin
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++;
}
}
如何修复此错误?更改
静态对象字符串[]args
到
静态环[]args
您的定义是Main方法将返回一个对象,但我看到没有返回语句。最重要的是将对象更改为void。对象意味着主方法需要某个返回语句。void意味着它不必有一个。进行此更改,代码至少会编译
这条线上还有一个问题:
int current = Convert.ToInt32(thelist[b]);
因为列表[b]尚未分配任何内容。您希望这样做:
int current = Convert.ToInt32(Line);
现在,代码应该几乎可以产生良好的输出。您还需要将Sort和WriteLine移动到一个单独的循环中,该循环在插入所有整数后运行。否则,现有循环在每次迭代时只输出当前最大的项,并且比需要的慢得多,因为它每次都重新排序
最后,使用循环填充变量的整个过程只是额外浪费了代码和CPU。您可以从file.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);
}
}
如果你不打算返回任何东西,将静态对象更改为静态voidMan,看看你建议的所有内容,我基本上意识到我根本不擅长这个。感谢您通读和超越,告诉我哪里的代码将是一个低效的混乱。编程是陡峭的曲线。坚持下去。没有人一开始就知道如何利用每一个小秘密。当我想到我的一些新生课程作业时,我会畏缩。
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);
}
}