【问题标题】:Array does not get recognized in other jButtons数组在其他 jButtons 中不被识别
【发布时间】:2015-07-28 23:36:52
【问题描述】:

我正在编写一个程序(在 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

我对此进行了谷歌搜索,发现它与变量的范围有关,但除此之外我找不到更多信息。这可能是一个非常愚蠢的问题,但我真的很感激一些帮助:)

【问题讨论】:

  • 定义两个方法范围之外的数组,例如班级水平
  • @Reimeus 非常感谢!这解决了我的问题!

标签: java arrays netbeans


【解决方案1】:

Car[] carArray = new Car[b]; 你应该在下面的方法中声明它。此链接将帮助您了解变量范围。

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'
    }
}

【讨论】:

  • 谢谢,这很有帮助!我一定会仔细阅读这些链接!
猜你喜欢
  • 1970-01-01
  • 2021-06-28
  • 2016-04-13
  • 2020-04-29
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
  • 2010-11-27
  • 2012-06-10
相关资源
最近更新 更多