[英]How to fix Error CS0161; not all code path return a value c#?
我是 c# 的新手,目前正在開發一個讀取文本文件路徑然后顯示該文件中最長單詞的程序。 這是我的代碼:
static void Main(string[] args)
{
Console.WriteLine("Enter the path for a text file: ");
var path = Console.ReadLine();
Console.WriteLine(LongestWord(path));
}
public static string LongestWord(string path)
{
var characters = new char[] { ' ', '.', ',', ';', '?', '\n', '\r' };
var content = File.ReadAllText(path);
var words = content.Split(characters);
var list = new List<int>();
if (File.Exists(path))
{
foreach (var word in words)
{
list.Add(word.Length);
}
int max = list.Max();
for (int i = 0; i < words.Length; i++)
{
var count = words[i].ToCharArray();
if (count.Count() == max)
{
return words[i];
}
}
}
else
{
return "You entered a file that could not be located";
}
}
如您所見,我嘗試使“Longestword”成為一種我可以在任何地方使用的方法。 這是我得到命名錯誤的時候。 如果我在同一個 Main class 中使用代碼,則代碼會以其他方式工作。
我嘗試了幾個“if”語句和異常,但似乎都沒有解決問題。
這里的問題是有一個執行路徑沒有遇到 return 語句。 特別是在文件計數和打開的位置,但是第二個 for 循環中的 if 語句永遠不會被評估為 true。
現在在正常執行下,這應該永遠不會發生,但這在技術上是可行的。 解決此問題的一種方法是在此循環后拋出異常。 但最好的辦法是解決邏輯。
如果您願意使用 LINQ,則:
foreach (var word in words)
{
list.Add(word.Length);
}
int max = list.Max();
for (int i = 0; i < words.Length; i++)
{
var count = words[i].ToCharArray();
if (count.Count() == max)
{
return words[i];
}
}
可以替換為: return words.OrderByDescending(w => w.Length).First();
否則應返回默認值,例如null
或列表的最后一個元素。
其他一些注意事項:使用字符串或數組時,可以使用.Length
屬性代替 Linq Extension .Count()
。 .Length
只是檢索存儲的值(快速),但.Count()
每次都會循環遍歷字符串/數組(盡管 Linq 已進行優化以避免此類額外工作)
if (count.Count() == max)
之后沒有返回語句。 您還應檢查文件是否不為空。 如果文件不存在,最好拋出異常。 您在檢查文件是否存在之前嘗試讀取文件,如果文件不存在,您將獲得異常。
static string? LongestWord(string path) {
var characters = new char[] { ' ', '.', ',', ';', '?', '\n', '\r' };
var list = new List<int>();
string result = string.Empty;
if (File.Exists(path)) {
var content = File.ReadAllText(path);
if(content.Length > 0) {
var words = content.Split(characters);
foreach (var word in words) {
list.Add(word.Length);
}
int max = list.Max();
for (int i = 0; i < words.Length; i++) {
var count = words[i].ToCharArray();
if (count.Count() == max) {
result = words[i];
}
}
return result;
} else {
return null; //Or throw exception
}
} else {
throw new FileNotFoundException();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.