在其他jButton中无法识别数组

时间:2015-07-28 15:05:38

标签: java arrays netbeans

我正在编写一个程序(在Netbeans中),它有两个按钮;一个将从用户获取输入并将其存储在对象中,然后将此对象存储在数组中。另一个将在jTextArea上打印出数组中的所有现有对象。

这是我的班级:

public class Car {
    public String brand;
    public String year;

  public Car (String brand, String year) {
      this.brand = brand;
      this.year = year;
  }


}

这是我写的代码:

private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
    int a = 0;
    int b = 1;

    Car[] carArray = new Car[b];
    carArray[a] = new Car (txtfBrand.getText(), txtfYear.getText());
    a++;
    b++;
}                                      

private void btnReadActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
    for (int i = 0; i < carArray.length; i++) {    //I get and error on this line for 'carArray'...
        txtaRead.setText(" " + carArray[i] + "\n");    //...And on this line, also for 'carArray'
    }
}

Add - 按钮下的代码的想法是获取用户输入并将其存储在carArray中。单击Read - 按钮后,我希望打印出carArray中的所有内容。我以为我用我的代码完成了这个,但我得到一个错误说:

cannot find symbol
  symbol: variable carArray
  location: class Car

我在上面搜索了一些,发现它与变量的范围有关,但我找不到更多。这可能是一个非常无趣的问题,但我真的很感激一些帮助:)

1 个答案:

答案 0 :(得分:1)

Car[] carArray = new Car[b]; you should declare this out side from the method as below. this links will help you to understand variable scope.

http://www.java-made-easy.com/variable-scope.html

http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm

Variable Scope Example Explanation

Java variable scope

Car[] carArray = new Car[b];
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
    int a = 0;
    int b = 1;


    carArray[a] = new Car (txtfBrand.getText(), txtfYear.getText());
    a++;
    b++;
}                                      

private void btnReadActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
    for (int i = 0; i < carArray.length; i++) {    //I get and error on this line for 'carArray'...
        txtaRead.setText(" " + carArray[i] + "\n");    //...And on this line, also for 'carArray'
    }
}