簡體   English   中英

如何在另一個類中更改變量的值,並且仍然能夠在另一個類中更改它的值?

[英]How do I change the value of a variable from another class and still be able to change it within the other class?

因此,我在那時還不到一年的編程工作中還是一個新手。 我對Java更加陌生(我以前做過C ++)。 因此,在名為Fighting的類中,我有一些變量,如numberHealthPotions,health,attackDamage等。 但是,在我的主要班級中,游戲中有些地方,角色拿起武器,拿起葯水或受傷。 我只需要一種方法就可以在我的主要班級中說他受傷了,然后更改角色健康狀況或其他任何因素的價值。

這只是我的代碼的一個片段,旨在為您提供一個想法...

else if(inputHKitchen.equalsIgnoreCase ("examine")){
                System.out.println("Examine what?");
                examineWhat = in.nextLine();
                if(examineWhat.equalsIgnoreCase("drawer")){
                    System.out.println("\tYou found a knife!");
                    attackDamage = 50;
                    System.out.println("\tYour attack damage has been increased!\n");
                    System.out.println(houseKitchen);
                }

如果您的變量是靜態的,則可能是

//note this variable must be public or protected
Player.HEALTH = 0;

如果它不是靜態的,那么

Player p = new Player();
p.HEALTH = 0;

我將為角色編寫一系列公共方法來管理這些不同的值。

例如,在類YourCharacter中:

private int attackDamage;

public void addDamage(int value)
{
    attackDamage += value;
}

然后在您的代碼段中:

if (examineWhat.equalsIgnoreCase("drawer")){
    yourCharacter.addDamage(50);
}

可以在java-gaming.org上找到許多有關Java的良好游戲編寫建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM