LemonyFresh
LemonyFresh

Reputation: 15

Making an array object from another Class in Java

Firstly, let me preface this by saying that I'm quite new to Java, so apologies if I mess up on any terminology or anything.

Now, secondly, on to my question.

I've made a String array in one class('Warranty'):

public class Warranty {

private int monthnum;
private String[] partscovered = new String[5]; {

    partscovered[0]= "Engine";
    partscovered[1]= "Mirrors";
    partscovered[2]= "Electrics";
    partscovered[3]= "Body";
    partscovered[4]= "Wheels";

}


  public Warranty(int monthnum,String[] partscovered) {

    this.monthnum = monthnum;
    this.partscovered= partscovered;

}



public void displaywarranty() {

    System.out.println("*******");
    System.out.println(8);
    System.out.println(partscovered);
    System.out.println("\n");

}

I'm trying to instantiate it in another class('VehicleTest'):

public class VehicleTest {

    public static void main(String[] args) {

         ......

        Warranty warranty = new Warranty(0,partscovered); //returns an error: 'partscovered cannot be resolved to a variable'
        warranty.displaywarranty();

          }


}

I want to print the array to the console of my IDE, but I'm a little stuck as to why I'm getting the above error message (i.e partscovered cannot be resolved to a variable). It seems to me as if I've done it right, but clearly I haven't so I'm a little stumped to be honest. Any help would be greatly appreciated! :)

Upvotes: 0

Views: 5065

Answers (1)

Paul Boddington
Paul Boddington

Reputation: 37645

There are three problems with this code.

Firstly, the way to print an array is

System.out.println(Arrays.toString(partscovered));

Secondly, you cannot pass partscovered to the Warrenty constructor because partscovered is a field of Warranty. You would have to make a separate variable. Something like

String[] pc = {"Steering Wheel", "Exhaust Pipe"};
Warranty warranty = new Warranty(0, pc);
warranty.displaywarranty();

Alternatively, you could avoid using a variable at all

Warranty warranty = new Warranty(0, new String[]{"Steering Wheel", "Exhaust Pipe"});

Finally, I personally dislike your use of an instance initializer to fill up the array partscovered with "Engine", "Mirrors" etc. This happens even if you pass an array to the constructor. Another way to provide a default array is to write a second constructor:

private String[] partscovered; // This is deliberately not assigned

public Warranty(int monthnum) {
    this.monthnum = monthnum;
    this.partscovered = new String[]{"Engine", "Mirrors", "Electrics", "Body", "Wheels"};
}

public Warranty(int monthnum,String[] partscovered) {
    this.monthnum = monthnum;
    this.partscovered = partscovered;
}

Upvotes: 2

Related Questions