Home > Software engineering >  Can't copy data from an array to another one
Can't copy data from an array to another one

Time:03-20

I'm trying to copy the data into the kilometres array but I got an error said can't convert type. How can I fix this?

public class Driving {
            public int[] Kilometers;
        
            public Tracking(int[] data) {
                for (int i = 0; i < data.length; i  ) {
                    Driving[] Kilometers = new Driving[i];
                    Kilometers[i] = data[i]; //can't convert int to driving
                }
                
            }
    }

CodePudding user response:

   public class Driving {
    private int[] kilometers;
    
    public void setKilometers(int[] kilometers) {
             this.kilometers = kilometers;
          }
    public int[] getKilometers() {
       return this.kilometers;
     }
    
    
    public void tracking(int[] data) {
        setKilometers(data) ;
    }
} 

You can do similar as above if your objective is to set the kilometers, however that job will be done by setter method itself.

CodePudding user response:

Something like this

public class Driving {
        public int[] Kilometers;
    
        public void Tracking(int[] data) {
            int[] Kilometers = new int[data.length];
            for (int i = 0; i < data.length; i  ) {
                Kilometers[i] = data[i];
            }
            
        }
}

CodePudding user response:

You can simple assign the data you are getting in parameter to class variable no need to loop see below code for reference

public class Driving {
    public int[] Kilometers;
    
    public void Tracking(int[] data) {
        this.Kilometers=data;

    }
}
  • Related