不能指向我的数组的第一个对象

时间:2013-05-17 14:10:54

标签: java arrays static

我有这个问题,我正在学习java并尝试做我的练习之一,我不能指向我创建的数组的第一个对象。

这里是代码:

    public class prova {
        public static void main(String[] args) {

                    int y=0;

                    int n=0;

                    int h=20, g=21,d=56,z=44;

                    int conf=100;

                    riga[] array=new riga[100];

                    array[n]= new riga(3,10,5,6);


                    while(conf !=105) {

                    array[n]= new riga(h++,g++,d++,z++);

                    array[n].nextbet=array[0].importobet;// i want to set the nextbet field of my current array to the importobet value of the first object in this array. Look the output down here.

                    System.out.println("ecco:"+array[n].nextbet);
                    n++;

                    conf++;

                    }
}

class riga {

//variabili

        static public int numerostep;
        static public double importoquota;
        static public double importobet;
        static public boolean esito;
        static public double cassa;
        static public double profitto;
        static public double nextbet;
   //costruttore
        public riga(int a,double d, double c,double f){

                numerostep=a;
                importobet=d;
                importoquota=c;
                cassa=f;


}
  //metodi
        public static void stampaRiga(int a, double b, double c,double f) {

                System.out.println("step:"+a+"***importo:"+b+"***quota:"+c+"***cassa:"+f);
}

}




}

我将问题写在它所在行附近的注释中。在此示例中,输出为:

21.0
22.0
23.0 
........

但它应该是:

21.0
21.0
21.0
........

2 个答案:

答案 0 :(得分:2)

array[n]= new riga(h++,g++,d++,z++);

每次迭代都会增加g,所以第一个输出是正确的

答案 1 :(得分:1)

那是因为你正在递增初始值h = 20 n = 0

array[n]= new riga(h++,g++,d++,z++);

1st iteration n=0 h++ ie 20+1=21  so h will have 21
2nd iteration n=1 h++ ie 21+1=22  so h will have 22
3rd iteration n=2 h++ ie 22+1=23  so h will have 23