[英]Java - method that returns a class instance to different class?
我是初學者,嘗試過搜索,但沒有任何結果,抱歉。 我有 2 個課程,我不知道如何鏈接獎勵硬幣(oneCoin/twoCoin/threeCoin),以便如果調用,它會將硬幣添加到 Bag 庫存中。 回報也可能不正確。
public class Bag {
private int oneCoin;
private int twoCoin;
private int threeCoin;
//etc
}
public class Thief {
public Thief(String name, int level) {
this.name = name;
this.health = level * 100;
this.level = level;
}
//problem code
public Bag rewardCoins(){
oneCoin =+ (int)(level-Math.random()*level/6);
twoCoin =+ (int)(level-Math.random()*level/2);
threeCoin =+ (int)((level-level/2)-Math.random()*(level-level/2));
return rewardCoins();
}
}
不尋求即時幫助,我只是不知道我應該閱讀什么來弄清楚。
編輯:我可能解釋得不好——我不能使用二傳手,因為 Bag 庫存中已經有東西了。 當小偷被“擊敗”時,我想將硬幣添加到庫存中。 就像丟掉戰利品一樣。 我不知道如何訪問 Thief 中的私有字段 one/two/threeCoin 以將它們添加到另一個類。 它們是 2 個不同的類,Thief.java 和 Bag.java
第二次編輯:對於閱讀本文的任何人,答案是將屬性和返回值更改為-
public Bag rewardCoins(){
int one = (int)(level-Math.random()*level/6);
int two = (int)(level-Math.random()*level/2);
int three = (int)((level-level/2)-Math.random()*(level-level/2));
return (new Bag(one, two, three));
}
你可能想要這樣的東西:
public class Thief {
private final String name;
private final int health;
private final int level;
public Thief(String name, int level) {
this.name = name;
this.health = level * 100;
this.level = level;
}
public Bag rewardCoins(Bag bag){
int oneCoin = bag.getOneCoin();
int twoCoin = bag.getTwoCoin();
int threeCoin = bag.getThreeCoin();
oneCoin =+ (int)(level-Math.random()*level/6);
twoCoin =+ (int)(level-Math.random()*level/2);
threeCoin =+ (int)((level-level/2)-Math.random()*(level-level/2));
Bag result = new Bag();
result.setOneCoin(oneCoin);
result.setTwoCoin(twoCoin);
result.setThreeCoin(threeCoin);
return result;
}
}
或這個:
public class Thief {
private final String name;
private final int health;
private final int level;
private Bag bag;
public Thief(String name, int level) {
this.name = name;
this.health = level * 100;
this.level = level;
}
public Bag rewardCoins(){
int oneCoin = bag.getOneCoin();
int twoCoin = bag.getTwoCoin();
int threeCoin = bag.getThreeCoin();
oneCoin =+ (int)(level-Math.random()*level/6);
twoCoin =+ (int)(level-Math.random()*level/2);
threeCoin =+ (int)((level-level/2)-Math.random()*(level-level/2));
Bag result = new Bag();
result.setOneCoin(oneCoin);
result.setTwoCoin(twoCoin);
result.setThreeCoin(threeCoin);
return result;
}
}
這得看情況。 查看您的代碼,我可以假設您希望小偷將硬幣獎勵給小偷之間共享的庫存。 在這種情況下,您可以將其作為小偷的變量並將其作為構造函數的參數傳遞。 這樣所有的竊賊都可以訪問同一個 Bag 對象。
public class Bag {
private int oneCoin;
private int twoCoin;
private int threeCoin;
//getters and setters
}
public class Thief {
private Bag bag;
public Thief(String name, int level,final Bag bag) {
this.name = name;
this.health = level * 100;
this.level = level;
this.bag=bag;
}
public void rewardOneCoin(){
bag.setOneCoin(bag.getOneCoin()+ (int)(level-Math.random()*level/6))
}
// Appropriate functions for two and three coins
}
如果你能給我更多的背景信息,我可能會為你提供更多幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.