如何在一个Java的另一个方法中将一个方法的变量作为变量?

在这里,我试图将我的’cash’变量从Player方法中包含在我的wagerBet()方法中的等式中。 目前Eclipse告诉我变量’cash’不能’静态引用非静态现金’。 我试着寻找关于这个问题意味着什么的解释,但我只是得到解释,使用更多的编程术语我不明白是因为我是这个东西的新手。

class Player { private ArrayListhand; private double cash, bet; public Player(double theCash) { cash = theCash; //'cash' variable here hand = new ArrayList(); } public static double wagerBet() { Scanner in = new Scanner(System.in); System.out.print("Wager a bet: "); double bet = in.nextDouble(); cash = cash - bet; // needs to be transferred here System.out.println("You wagered " + bet + ". " + "Now you have " + cash + " cash left."); return bet; } public void rewardBet(double bet) { cash = cash + (bet * 2); //cash and bet variable needs to be transferred here as well System.out.println("You now have " + cash + "cash."); } 

有什么建议么?

cash变量不属于任何方法。 它是该类的实例成员。 您无法从静态方法访问它。 如果您只需要在那里读取其值,则将该方法设置为非静态,或将“现金”作为参数传递给它。

您可能想要了解一些Java基础知识:

http://docs.oracle.com/javase/tutorial/java/javaOO/index.html

您试图在静态方法中使用Player的属性。 静态方法不是实例的一部分,因此它不知道什么是“现金”(因为它对每个Player实例而不是单个变量都是唯一的)。

从wagerBet中删除“static”,使其成为Player的方法。 这样它对每个玩家来说都是独一无二的,因此它会知道使用同一个玩家的“现金”。

删除静态

 public static double wagerBet() 

只有一个真正的问题。 要了解static是什么。

基本方法,直到你足够好,是根本不使用static 。 在所有情况下删除它而不是“主”(你必须保持在那里)。