-5

我有这个问题,我正在学习 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
........
4

2 回答 2

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

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

于 2013-05-17T14:17:56.743 回答
1

那是因为你正在增加它 initiall 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
于 2013-05-17T14:30:04.277 回答