0

I cant use Lists, it must be in tables. How to copy a table to another table greater by 1? Im adding some elements to my table and if there is not enough space i want create new/copy table greater by 1.

Code:

Scanner sc = new Scanner(System.in);
String addNew;
String[] newTab = new String[1];

addNew = sc.next();

for(int i = 0; i<newTab.length; i++) {
if (newTab[i] == null) {
    newTab[i] = addNew;
}
else {
    //here i want to create new table greater than first one
}
}

Trying with Array.CopyOf but still got error java.lang.ArrayIndexOutOfBoundsException: 1

Code:

int defTab = 1;
for(int i = 0; i<newTab.length; i++) {
        if (newTab[i] == null) {
            newTab[i] = addNew;
            //f
            for(int j=0; j<newTab.length; j++) {
                System.out.println("array content "+newTab[j]);
            }
        }
        else {
            String[] newTab2 = Arrays.copyOf(newTab, defTab+1);
            for(int j = 0; j<newTab2.length; j++) {
                if (newTab2[j] == null) {
                    newTab2[j] = addNew;
                    //f
                    for(int k=0; k<newTab2.length; k++) {
                        System.out.println("array content "+newTab[k]);
                    }
                }
            }
        }
    }
dmat
  • 51
  • 7
  • 2
    Did you consider using Arrays.copy static method? – Dawid Pura Feb 21 '16 at 12:10
  • What is a table? You mean array – Jens Feb 21 '16 at 12:14
  • in case the intend of `if (newTab[i] == null)` is to check whether there is another free space in `newTab` at position `i` it will lead to a NullPointerException! – SevenOfNine Feb 21 '16 at 12:18
  • 1
    Look at the size of the array you allocated. There is probably a better example for what your looking for here: http://stackoverflow.com/questions/14837185/how-can-we-dynamically-allocate-and-grow-an-array – Mike Feb 21 '16 at 13:03

0 Answers0