我正在编写一个程序(在 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
我用谷歌搜索了一些,发现它与变量的范围有关,但我找不到更多的信息。这可能是一个非常菜鸟的问题,但我真的很感激一些帮助:)
最佳答案
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
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'
}
}
关于java - 其他 jButton 无法识别数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31680219/