我正在接受C#,作为初学者练习,我试图编写一个简单的铁拳锦标赛名单。问题是,我找不到如何将类Fighter
的方法应用到整个战士列表的方法,因为没有变量的名称,或者至少我认为这是问题。
using System;
using System.Collections.Generic;
namespace TekkenConsoleTournament
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ("Enter nicknames of players, finished by 0: \n");
int numFighter=0;
String nickname;
List <Fighter> allFighters = new List<Fighter>();
while ((nickname = Console.ReadLine()) != "") {
allFighters.Add(new Fighter(nickname));
numFighter ++;
}
Console.WriteLine(allFighters.ForEach(Fighter.getName()));
Console.WriteLine(foreach(Fighter in allFighters) {getName();});
//for (int counter = 0; counter <= fighter; counter++) {
// Fighter[counter.getName();
//}
}
}
}
和Fighter.cs
using System;
namespace TekkenConsoleTournament
{
public class Fighter
{
private int matches, won, lost, draw;
String name;
public Fighter (String name)
{
this.matches = this.won = this.lost = 0;
this.name = name;
}
public void wonMatch()
{
matches++;won++;
}
public void lostMatch()
{
matches++;lost++;
}
public void drawMatch()
{
matches++;draw++;
}
public int[] getStats()
{
int[] stats = {this.matches,this.won,this.lost,this.draw};
return stats;
}
public String getName()
{
return this.name;
}
}
}
首先,我想打印所有战士的名字,然后可能是统计数据,然后作为练习尝试让代码记住谁战斗谁并根据战斗结果将它们放在二维矩阵中。 / p>
答案 0 :(得分:1)
使用foreach
循环?
foreach(var fighter in allFighters)
{
// do something with fighter
var name = fighter.getName();
Console.WriteLine(name);
}
如果没有使用您的getName
或field
名称来获取当前战斗机的名称,我认为有一种property
方法。
你的错误是你在ForEach
方法中放置了Console.WriteLine
循环。你应该这样做。这种语法错了:
foreach(Fighter in allFighters)
应该是这样的:
foreach(Fighter fighter in allFighters)
或者您可以使用var
,如上面的代码所示。
答案 1 :(得分:1)
你很亲密,但并不完全。尝试以下选项:
Console.WriteLine(string.Join(", ", allFighters.Select(f => f.getName())));
allFighters.ForEach(fighter => Console.Writeline(fighter.getName()));
foreach (Fighter f in allFighters)
{
Console.WriteLine(f.getName());
}