【发布时间】:2023-04-01 17:03:01
【问题描述】:
我正在学习 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;
}
}
}
首先,我想打印所有战士的名字,然后可能是统计数据,然后作为练习尝试让代码记住谁与谁战斗,并根据战斗结果将它们放入二维矩阵中。
【问题讨论】:
-
你能提供你的战斗机课程吗?你到底想要什么,显示所有战士的名字?
-
您想将 Console.WriteLine 代码放在 foreach 循环中。
-
一些指针(约定):类、方法名和属性名应该是 PascalCased(即 public void DrawMatch())。仅获取/设置值的方法通常应该是属性(即 public String getName() 应该是 public String Name{ get { return this.name; } }。你可以(并且 I 会说 应该)使用
string而不是String(就像你使用int而不是Int32 -
嗯.. 有什么特别的原因吗?从我对 Java 的摆弄中,我习惯了大写的 S。