[英]C# I'm using string arrays, and I was hoping to use a “foreach” to Display a list of them
我相信除了foreach語句外,我的大部分代碼在大多數情況下都是正確的。 但是由於程序未編譯,我無法對其進行測試。 我將不勝感激,即使我的結構需要進行一些更改,我也將不勝感激。
private static void PickScreen(Human myHuman)
{
var tries = 3;
bool answer = false;
string choice= "";
string[] choices = new string[6];
choices[0] = "Name";
choices[1] = "Age";
choices[2] = "Scar Type";
choices[3] = "Weapon";
choices[4] = "Hero Status";
choices[5] = "Potions";
DisplayNewScreenHeader();
Console.WriteLine(" What screen would you like to go to?");
Console.WriteLine();
foreach (string i in choices)
{
Console.WriteLine(" Screen Choice: {0}", choices[]);
}
Console.WriteLine();
Console.WriteLine(" Or you can type in " + "\"Default\"" + "to not have to do any of the query screens and have your character have default settings.");
while(tries > 0)
{
Console.WriteLine(" Choice: ");
choice = Console.ReadLine();
if (choice.Equals("name", StringComparison.OrdinalIgnoreCase))
{
DisplayGetHeroName(myHuman);
answer = true;
}
else if (choice.Trim().Equals("age", StringComparison.OrdinalIgnoreCase))
{
DisplayGetUsersAge(myHuman);
answer = true;
}
else if (choice.Trim().Equals("Scar Type", StringComparison.OrdinalIgnoreCase))
{
DisplayGetScar(myHuman);
answer = true;
}
else if (choice.Trim().Equals("weapon", StringComparison.OrdinalIgnoreCase))
{
DisplayGetWeapon(myHuman);
answer = true;
}
else if (choice.Trim().Equals("Hero Status", StringComparison.OrdinalIgnoreCase))
{
DisplayGetHeroStatus(myHuman);
answer = true;
}
else if (choice.Trim().Equals("Potions", StringComparison.OrdinalIgnoreCase))
{
DisplayAddBackpackItems(myHuman);
answer = true;
}
else if (choice.Trim().Equals("Default", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine(" Looks like you went with the lazy way. Anyways go conquer basements, and become ruler of stuff!");
}
else
{
Console.WriteLine(" Dog gone it, yer Missed up a bit tad.");
Console.WriteLine();
Console.WriteLine(" Try again");
tries -= 1;
}
}
if (answer == false)
{
DisplayNewScreenHeader();
Console.WriteLine(" Since you're incompetent you no longer have the option to pick your query screens. They will simply go in order now.");
DisplayGetHeroName(myHuman);
DisplayGetUsersAge(myHuman);
DisplayGetScar(myHuman);
DisplayGetWeapon(myHuman);
DisplayGetHeroStatus(myHuman);
DisplayAddBackpackItems(myHuman);
DisplayReturnPrompt();
}
}
在foreach
循環中,隨着循環的繼續,您的變量(在本例中為i
)被設置為枚舉中的每個值。 您需要更改:
foreach (string i in choices)
{
Console.WriteLine(" Screen Choice: {0}", choices[]);
}
至:
foreach (string i in choices)
{
Console.WriteLine(" Screen Choice: {0}", i);
}
您的foreach
循環應如下所示,因為i
實際上是choices
項之一
foreach (string i in choices)
{
Console.WriteLine(" Screen Choice: {0}", i);
}
至於foreach
遍歷您的數組, i
將有值:
choices[1]
choices[2]
choices[3]
.......
etc
更改
Console.WriteLine(“屏幕選擇:{0}”,options []);
至
Console.WriteLine(“屏幕選擇:{0}”,i);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.