Tin*_*iny 0 c# arrays text-files
试图创建一个简单的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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是因为你两次调用LoadWords().
你应该写:
string[] WordsArray= LoadWords();
if (WordsArray != null)
{
Console.WriteLine("File Loaded...\n\n");
DisplayWordsArray(WordsArray);
...
Run Code Online (Sandbox Code Playgroud)