gpt4 book ai didi

java - 出现错误 : non-static method getTotalPlayers() cannot be referenced from a static context

转载 作者:行者123 更新时间:2023-12-01 23:52:28 26 4
gpt4 key购买 nike

我不明白我在这里做错了什么,也不明白这里的任何东西在没有这样声明的情况下如何是静态的。我只需要在这里指出正确的方向。

测试代码:

public class PaintballPlayerTest
{
//Test program for PaintballPlayer assignment

public static void main (String [] args)
{
//Part 1 check constructor & toString --(make sure ID is working too)
PaintballPlayer sheldon = new PaintballPlayer ("Sheldon", "Lee", "Cooper");
PaintballPlayer leonard = new PaintballPlayer ("Leonard", "Hofstadter");
PaintballPlayer amy = new PaintballPlayer ("Amy", "Farrah", "Fowler");

System.out.println(sheldon);
System.out.println(leonard);

//Part 2 test getTotalPlayer --should be 3
System.out.println("The team has this many players " + PaintballPlayer.getTotalPlayers());

我的代码:

import java.util.*;

public class PaintballPlayer
{
private String firstName, middleName, lastName;
private String secFirst, secLast;
private int id;
private int count;
private static int totalPlayers;
private int playerID;
private int players;

public PaintballPlayer(String first, String middle, String last)
{
count = 0;
id = totalPlayers++;
players = count++;
firstName = first;
middleName = middle;
lastName = last;
}

public PaintballPlayer(String f, String l)
{
this (f,"",l);
id = count++;


}


public PaintballPlayer()
{
totalPlayers++;
}

public static int getTotalPlayers()
{
return totalPlayers;
}

public String toString()
{
String name;
String n;
name = firstName + " " + middleName + " " + lastName;

return name;

}


public int getPlayerID()
{
playerID = count;
return playerID;
}
}

同样,我的问题出在 getTotalPlayers() 方法上。

编辑:这是我编辑的代码,应用了所提供的修复程序。谢谢!

最佳答案

getTotalPlayers() 不是静态方法,因此您需要 PaintballPlayer 的实例来调用此方法。

如果您想在 PaintballPlayer 中存储玩家总数,您需要一个静态属性(所有实例的引用相同):

class PaintballPlayer {

private static int totalPlayers;

public PaintballPlayer() {
totalPlayers++;
}

public static int getTotalPlayers() {
return totalPlayers;
}
}

关于java - 出现错误 : non-static method getTotalPlayers() cannot be referenced from a static context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16153083/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com