类对象和数组 - 为什么它返回“空”? [考试] [英] objects classes and arrays - why is it returning 'null' ? [java]

查看:123
本文介绍了类对象和数组 - 为什么它返回“空”? [考试]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了创建一个包含3阵列报表对象小班。在创建对象的这些阵列被初始化用的值。然而,当我测试类,例如,见有什么部门数组中,它打印出的数组元素都为null。为什么?

I wrote a small class that creates a report object containing 3 arrays. At creation of the object these arrays are initialised with values. However when i test the class to see for example what's in the departments array, it prints out that the array elements are null. why?

 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

测试类:

 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

感谢

巴巴

推荐答案

请像这样

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  

其实你正在创造新的数组对象,您的本地构造那些构造越来越初始化。

Actually you are creating new arrays objects local to your constructor those are getting initialized in constructor.

你的类字段会使用上述code被初始化。

your class fields will be initialized using the code above .

如果你没有错做比请参阅本文档它也将更好地清除您的理解

**

:**
上述code会给你前pression的非法启动

:** Above code will give you illegal start of expression

下面是工作code

 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
 } 

这篇关于类对象和数组 - 为什么它返回“空”? [考试]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆