如何在Java中使用变量?

Rus*_*ell 1 java variables swing 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() {
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我将要使用的所有变量都是实例变量,所以我要问的是,我应该这样做,还是应该尝试将我的大多数变量限制在他们所使用的每个方法中? d用于?

MBy*_*ByD 5

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