majesticUnicorn
majesticUnicorn

Reputation: 29

Array does not get recognized in other jButtons

I'm writing a program (in Netbeans) which has two buttons; One which will take the input from the user and store it in an object, and then store this object in an array. And another one which will print out all existing objects in the array on a jTextArea.

This is my class:

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

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


}

And this is the code I have written to go with it:

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

The idea for the code under the Add-button is to take the user input and store it in the carArray. When the Read-button then is clicked, I want everything in the carArray to be printed out. I thought I had accomplished this with my code, but I get an error saying:

cannot find symbol
  symbol: variable carArray
  location: class Car

I googled some on this and found out that it had something to do with the scope of variables but I couldn't find out much more than that. This maybe a very noobish question, but I would really appreciate some help:)

Upvotes: 1

Views: 49

Answers (1)

sushi
sushi

Reputation: 141

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

Upvotes: 1

Related Questions