java - 在 Java 中如何使用变量?

标签 java swing variables coding-style instance-variables

我在过去一年的空闲时间里一直在学习 Java,到目前为止,我对如何正确使用变量一无所知。我的意思是,我应该更喜欢使用实例变量,还是只在单个方法中使用变量。

例如,这是我写的一段代码:

public class arsenalTroop {
    String[][] troopStats;
String[][] weaponStats;
String[][] armorStats;
String[][] animalStats;
String[] troops;
String[] weapon;
String[] armor;
String[] animal;
JLabel[] troopsArray;
int troopTotal;
int weaponTotal;
int armorTotal;
int lordTotal;
int animalTotal;

JFrame arsenalLordFrame = new JFrame();
JTextField name = new JTextField();
JLayeredPane lP = new JLayeredPane();
JLayeredPane fP = new JLayeredPane();
JLayeredPane ldP= new JLayeredPane();
JLabel siegeLabel = new JLabel();
JComboBox weaponCB;
JComboBox armorCB;
JComboBox animalCB;
JLabel siegeText = new JLabel();
JButton addWep = new JButton();
JButton addName = new JButton();
JButton addArmor = new JButton();
JButton addAnimal = new JButton();
JButton ntr = new JButton();
JButton nwe = new JButton();
JButton nar = new JButton();
JButton nan = new JButton();

JButton newWeaponButtonArray[] = new JButton[6];
JButton newArmorButtonArray[] = new JButton[6];
JButton newAnimalButtonArray[] = new JButton[6];

Border whiteBorder = BorderFactory.createLineBorder(Color.white);
Border greyBorder = BorderFactory.createLineBorder(Color.gray);

boolean[] weaponFree = new boolean[6];
boolean[] armorFree = new boolean[6];
boolean[] animalFree = new boolean[6];

JButton done = new JButton();

public void arsenalTroopGui() {

如您所见,我将要使用的所有变量都是实例变量,所以我想问的是,我应该这样做,还是应该尝试将大部分变量限制在每个方法中它们会被用在什么地方?

最佳答案

经验法则:变量应在尽可能小的范围内声明。

关于java - 在 Java 中如何使用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9597691/

相关文章:

java - 是否有可能使用反射获得 volatile 字段?

java - Android-动态添加项目到 ScrollView

java - 自动调整 JButton 图标大小

java - 绘图/绘图不连续(涉及鼠标事件)

Bash - 读取变量和直接分配变量有什么区别?

c# - 在 C# 中设置/获取命令行系统变量

c++ - For循环设置变量条件

java - 将 QByteArray 反序列化为 Java 数据类型

java - JavaFX 的金属外观

java - 如何在覆盖文件之前检查文件是否为空?