Java 我能';不要在类中设置值

Java 我能';不要在类中设置值,java,Java,我上了两节课。第一个是玩家类,第二个是包。我想要的是在main()中打印玩家的分数。在Bag中,我计算分数,并想在Player中设置分数。这是行李类的一部分 public void count( int number) { ............. scr=k*2;//gives an int setScore(scr);//set the score in Player class } 玩家: public class Player { public Player()

我上了两节课。第一个是
玩家
类,第二个是
。我想要的是在
main()
中打印玩家的分数。在
Bag
中,我计算分数,并想在
Player
中设置分数。这是
行李
类的一部分

 public void count( int number)
 { ............. 
   scr=k*2;//gives an int
   setScore(scr);//set the score in Player class
 }
玩家:

public class Player {

public Player() {
}

private String name;
private int score;

public Player(String name, int score) {
    this.name = name;
    this.score = score;
}
 public String getName() { 
     return name;
 }

public void setScore(int score) {
    this.score = score;
}

public int getScore() {
    return score;
}
在main()中,我尝试使用以下代码打印分数,但无法:

Player p=new Player();
System.out.println( p.getScore());
它返回我
score=0
(我在main的乞讨中设置了它)

我希望你能理解我想说的话。

如果你想为某个球员设定分数,你需要调用该对象的
setScore
。例如:

public void count(int number)
{
    scr = k * 2;
    player.setScore(scr);
}
其中
player
player
类型的变量

但是,这不会影响新玩家的得分:

这仍然会打印0,因为新玩家的分数仍然是0。您需要打印出您在
count
内设置分数的玩家的分数

很难给您提供比这更具体的信息,因为我们不知道应用程序的其余部分是如何结合在一起的,但是假设每个玩家都有一个独立的分数,您应该考虑在
count
方法中要更改哪个玩家的分数。

更改此值

public void count(int number)
{ 
    Player p=new Player();
    scr=k*2;//gives an int
    p.setScore(scr);//set the score in Player class
}

为了让它工作,Bag类应该有一个对Player类的引用。因此,基本上您应该更改代码以遵循以下模式

class Bag
{
  private Player p;

  public void setPlayer(Player pp)
  {
    p=pp;
  }

  public Player getPlayer()
  {
    return p;
  }

 public void count( int number)
 { 
   scr=k*2;//gives an int
   p.setScore(scr);//set the score in Player class
 }
}
你的主要方法是什么

Player p=new Player();
Bag b=new Bag();
b.setPlayer(p);
b.count(5);
System.out.println( p.getScore());

玩家和包是不同的类,假设你想在包类中做一些计算,这些计算将引用玩家类,这些值将需要在玩家类中,包类需要有玩家引用。因此,您需要在这两个类中进行一些更改

更改计数方法,如下所示

公开无效计数(玩家p,整数){………
scr=k*2;//给出一个int p.setScore(scr);//在Player中设置分数 类}

并将主要方法更改为如下所示

玩家p=新玩家();b袋=新袋();b、 计数(p,5); System.out.println(p.getScore())


你在哪里叫set?你只需要创建一个播放器并打印出来。这是一个问答网站。你问问题,我们回答。问题的定义特征是,它以问号结尾(“?”,ASCII码0x3F,在大多数键盘上,它可以在右shift键旁边找到。)如果不观察完整的应用程序,很难解释。
Player p=new Player();
Bag b=new Bag();
b.setPlayer(p);
b.count(5);
System.out.println( p.getScore());