【发布时间】:2019-02-14 15:07:56
【问题描述】:
尝试创建一个简单的 Hangman 游戏,其中读取外部文本(称为 words.txt)并将其中的字符串导入称为 WordsArray 的字符串数组。
程序编译得很好,但是,在显示填充数组的内容之前,它要求我输入文件名两次(参见下面的 foreach 循环)
有人可以确定为什么它在显示之前两次询问我的文件名吗?
(另外,更一般地说,我的重构是否适合这个简单的应用程序?)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static string [] LoadWords()
{
bool repeat = true;
while (repeat)
{
Console.WriteLine("Please enter the name of a file:");
string filename = Console.ReadLine();
try
{
string[] WordsArray = File.ReadAllLines(filename);
if (WordsArray.Length == 0)
return null;
else
return WordsArray;
}
catch (FileNotFoundException msg)
{
Console.WriteLine("\n Check the file exists!");
}
}
return null;
}
static void DisplayWordsArray(string [] WordsArray)
{
foreach (string word in WordsArray)
Console.WriteLine(word);
}
static void Main(string[] args)
{
string[] WordsArray= new string[10];
if (LoadWords() != null)
{
Console.WriteLine("File Loaded...\n\n");
WordsArray = LoadWords();
DisplayWordsArray(WordsArray);
}
Console.ReadLine();
}
}
}
【问题讨论】:
-
调用
File.Exists( ... )来确定文件是否可行,而不是在不可行时捕获错误。 -
它要求输入文件名两次,因为你调用了两次
LoadWords() -
我知道对 LoadWords() 的调用出现在选择语句中,当其结果与 null 进行比较时。但是,在这种情况下,我认为返回的结果只会被调用......而不是其中的完整实现。
-
每次调用方法时,都会执行方法代码。如果要多次使用返回值,请将其保存到变量中。
-
@ΩmegaMan 根据 Eric Lippert 的说法,OP 的设计是正确的 - 查看这篇博文的“外生异常”部分:blogs.msdn.microsoft.com/ericlippert/2008/09/10/…
标签: c# arrays text-files