我编写了一个创建包含 3 个数组的报告对象的小类。在创建对象时,这些数组用值初始化。但是,当我测试类以查看例如部门数组中的内容时,它会打印出数组元素为空。为什么?
class Report
{
// declare instance variables (arrays)
public String[] departments = new String[4] ;
public double[] grossTotals = new double[4] ;
public double[] taxTotals = new double[4] ;
// constructor
public Report(){
// declare, create and initialise all in one statement
String[] departments = {"Accounting", "Sales", "HR", +
"Administration"} ;
double[] grossTotals = {0.0, 0.0, 0.0, 0.0} ;
double[] taxTotals = {0.0, 0.0, 0.0, 0.0} ;
} // END constructor
} // class Report
Run Code Online (Sandbox Code Playgroud)
测试类:
class TestReport
{
public static void main(String[] args) {
// create report object
Report r = new Report();
for (int i = 0; i <= 3 ; i++ )
{
System.out.println(r.departments[i]) ;
}
} //end main
} // end test class
Run Code Online (Sandbox Code Playgroud)
谢谢
巴巴
弄成这样
public Report(){
// declare, create and initialise all in one statement
this.departments = {"Accounting", "Sales", "HR", +
"Administration"} ;
this.grossTotals = {0.0, 0.0, 0.0, 0.0} ;
this.taxTotals = {0.0, 0.0, 0.0, 0.0} ;
} // END constru
Run Code Online (Sandbox Code Playgroud)
实际上,您正在创建构造函数本地的新数组对象,这些对象正在构造函数中初始化。
您的类字段将使用上面的代码进行初始化。
**
:** 上面的代码会给你非法的表达式开始
这是工作代码
class Report
{
// declare instance variables (arrays)
public String[] departments = null;
public double[] grossTotals = null;
public double[] taxTotals = null;
// constructor
public Report(){
this.departments = new String[]{"Accounting", "Sales", "HR", "Administration"} ;
this.grossTotals = new double[]{0.0, 0.0, 0.0, 0.0} ;
this.taxTotals = new double[]{0.0, 0.0, 0.0, 0.0} ;
} // END constructor
}
Run Code Online (Sandbox Code Playgroud)