类变量如何访问java,如何从另一个类(java)的主类访问变量?

I'm making a cookie clicker clone in java to practice my java skills and I have a small problem, I have variables that are declared in the main method that I want to access from an ActionListener class. Here is some sample code from the ActionListener class. the the int variables (ex. clicks, grandamaCost) and the JTextFields (ex. display, cpsDisplay) are all in the main method. I was wondering how I could have access to variables in the main method so that this code could work in the other class. Thanks!

@Override

public void actionPerformed(ActionEvent e) {

JButton b = (JButton) e.getSource();

button(b.getText());

}

public void button(String input) {

switch (input) {

case "Cookie":

clicks++;

display.setText("Cookies: " + clicks + "");

cpsDisplay.setText("CPS: " + cps);

break;

case "Buy grandma":

if (clicks >= grandmaCost) {

grandmas++;

clicks = clicks - grandmaCost;

grandmaCost = (int) ((.15 * grandmaCost) + grandmaCost);

cps++;

}

display.setText("Cookies: " + clicks + "");

prices[0].setText("$" + grandmaCost);

cpsDisplay.setText("CPS: " + cps);

break;

case "Buy monkey":

if (clicks >= monkeyCost) {

monkeys++;

clicks = clicks - monkeyCost;

monkeyCost = (int) ((.15 * monkeyCost) + monkeyCost);

cps = cps + 2;

}

display.setText("Cookies: " + clicks + "");

prices[1].setText("$" + monkeyCost);

cpsDisplay.setText("CPS: " + cps);

break;

case "Buy Teemo":

if (clicks >= teemoCost) {

teemos++;

clicks = clicks - teemoCost;

teemoCost = (int) ((.15 * teemoCost) + teemoCost);

cps = cps + 3;

}

display.setText("Cookies: " + clicks + "");

prices[2].setText("$" + teemoCost);

cpsDisplay.setText("CPS: " + cps);

break;

}

}

}

解决方案

Your variables should be fields.

Fields are declared outside of a class's methods and are usually found right below the class declaration. Fields can be accessed by all methods of a class.

They can also be accessed from other classes (unless they are private) using the dot operator.

If a field is marked with static, its class name is used to reference it.

If a field is not static, an object of its class is used to reference it.

Example

public class Man {

public String name; //this is a field

public static String gender = "Male"; //this is a static field

public Man(String newName) {

name = newName; //assigns the value of a field from within a method

}

}

and another class...

public class Main {

public static void main(String[] args) {

Man bob = new Man("Bob");

System.out.println(bob.name); //referenced from object, prints Bob

System.out.println(Man.gender); //referenced from class name, prints Male

}

}

And to have more control over the access of your fields, you can use getters and setters. Take a read!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值