문제

my problem is i am not able to update the value of an object array...

The code is :

public class GlobalVariable {

    public int noOfSms = 0;
    public CheckingClass object = new CheckingClass ();
    public static void main(String[] args) {
       GlobalVariable call = new GlobalVariable ();
       call.driver();
    }

    private void driver() {
        for(int i = 0 ; i < 3 ; i++){
        object = CheckingFun();

     //   System.out.println("The No Of Sms"+noOfSms);
       System.out.println("Array Value"+object.array[noOfSms] + "     The number value"+object.number);
        }
    }

    private CheckingClass CheckingFun() {

        System.out.println("The No Of Sms "+noOfSms + "\n");
        object.array[noOfSms] = noOfSms;
        object.number = noOfSms;
        noOfSms = noOfSms + 1;

        return object;

    }

The other class is :

public class CheckingClass {
public int number ; 
public int[] array = new int [5];

}

Here object is an object of another class. My problem is in this line

object.array[noOfSms] = noOfSms;

The output is as follows

The No Of Sms 0

Array Value0     The number value0
The No Of Sms 1

Array Value0     The number value1
The No Of Sms 2

Array Value0     The number value2

What i don't understand is that why isn't the value of array updated. When the value of number which is also an attribute of the object is updated.

But the output i want is :

 Array Value0     The number value0
The No Of Sms 1

Array Value1     The number value1
The No Of Sms 2

Array Value2    The number value2
도움이 되었습니까?

해결책

You're printing array[0] each time in your output, while each loop is updating array[0]. array[1], etc.

Edit:

You're incrementing noOfSms at the end of CheckingFun(). So for the first pass, you set array[0] = 0, but before you reach your println, noOfSms has been incremented and is now 1. So you print array[1], which has not been initialized.

다른 팁

object.array[0] You repeatedly calling this function for three times

So array[0] value is 0

`object.array[i]`
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top