java - copy array and add 1 to its size using printall() method to return all int in new array -


this homework assignment have not been able complete. close, having trouble understanding how finish. appreciated.

  • implement class arrayplus1() takes integer array data , int x size. create method inside class arrayplus1() creates new array length 1 greater data’s length.
  • then create method copy data’s elements new array , add value of x last element of array.
  • create printall() method return integers in new array.
  • i not sure size = part.

code:

package addarray19;  class arrayplus1{   int[]array ={1,2,3,4,5};   int[]newarray = array;   int size;   int data;     public arrayplus1(int i){     size = i;   }    class arrayadd{     int[]newarray = new int[array.length +1 ];   }    void printall(){     for(int = 0; < array.length; i++){       newarray[i] = array[i];         }     array = newarray;        }   void copy(){     system.arraycopy(array, 0, newarray, 0, array.length);     newarray[5] = 5;   }  }  public class addarray19{    public static void main(string[] args) {      addarray19 array = new addarray19();      array.printall();   } }   

if i'm reading requirements correctly, you're supposed append int x data array. based on assumption, instruction write routine first "grow" data array might implemented readily enough. first, set default 1 (because adding empty array should 1 element array). next, check data isn't null. if isn't take its' length , add 1 size. return new int[] of length size like

static int[] growarray(int[] data) {     int size = 1;     if (data != null) {         size = 1 + data.length;     }     return new int[size]; } 

next, method add array first grow copy values , append new element @ end. like,

private static int[] addtoarray(int[] data, int x) {     int[] array2 = growarray(data);     if (data != null) {         system.arraycopy(data, 0, array2, 0, data.length);     }     array2[array2.length - 1] = x;     return array2; } 

then, can implement required arrayplus1 constructor like

private int[] data; public arrayplus1(int[] data, int x) {     this.data = addtoarray(data, x); } 

next, printall should like

public void printall() {     system.out.print(data[0]);     (int = 1; < data.length; i++) {         system.out.printf(", %d", data[i]);     }     system.out.println(); } 

finally, main() method should instantiating arrayplus1 instances... example,

public static void main(string[] args) {     int[] in = { 1, 2, 3 };     int x = 4;     arrayplus1 = new arrayplus1(null, 1);     a.printall();     arrayplus1 b = new arrayplus1(in, x);     b.printall(); } 

and output is

1 1, 2, 3, 4 

Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -