从Java中的另一个类创建数组对象

时间:2015-11-07 17:24:42

标签: java arrays string class constructor

首先,让我先说一下我是Java的新手,所以如果我搞任何术语或任何东西,请道歉。

现在,其次,关于我的问题。

我在一个类中创建了一个String数组('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");

}

我正在尝试在另一个类('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();

          }


}

我想将数组打印到我的IDE的控制台,但我有点担心为什么我收到上述错误消息(即partscovered cannot be resolved to a variable)。在我看来好像我做得对,但很明显我没有这样做,说实话我有点难过。任何帮助将不胜感激! :)

1 个答案:

答案 0 :(得分:2)

此代码存在三个问题。

首先,打印数组的方法是

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

其次,您无法将partscovered传递给Warrenty构造函数,因为partscoveredWarranty的字段。你必须创建一个单独的变量。像

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

或者,您可以避免使用变量

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

最后,我个人不喜欢您使用实例初始化程序将数组partscovered填充为"Engine""Mirrors"等。即使您将数组传递给构造函数,也会发生这种情况。提供默认数组的另一种方法是编写第二个构造函数:

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