简体   繁体   中英

How to increase size of array [a][b] every time I call a method?

public static int arraysize=1;
public String namabuku;
public String penulis;
public String Kategori;
public String buku[][]=new String[arraysize][3];
public static int a=0;
public void isiData(String kategori, String buku, String penulis){
    this.buku[a][0]=kategori;
    this.buku[a][1]=buku;
    this.buku[a][2]=penulis;
    arraysize++;
    a++;
}

Hi guys I tried to increase my array length every time I call a method named "isiData", but it didn't work. I already checked the increment, but nothing wrong with it. Is there any way to increase its length every time I use the method? I want to make a simple way to input book, category, and its author using array.

You cannot increase the size of array. There are 3 approaches to solve this problem:

  1. Use ArrayList as suggested by others.
  2. You can create another temp array of size one greater than the previous array and then copy the temp array to already created array.
  3. You can use the copyOf(array, size) function of Arrays in Java

For example:

previousArray = Arrays.copyOf(previousArray , arraysize + 1);

arraysize += 1

Just try this Approach:

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

/**
 *
 * @author Maverick
 */
public class Buku {

    public static int arraysize;
    public String namabuku;
    public String penulis;
    public String Kategori;
    public List<List<String>> bukuList = new ArrayList<List<String>>();

    public static void main(String[] args) {
        Buku n = new Buku();
        for (int i = 0; i < 5; i++) {
            n.isiData("ab" + i, "cd" + i, "ef" + i);
        }

        n.arraysize = n.bukuList.size();
        for (int i = 0; i < n.bukuList.size(); i++) {
            System.out.println(n.bukuList.get(i).toString());
        }
    }

    public void isiData(String kategori, String buku, String penulis) {
        bukuList.add(Arrays.asList(kategori, buku, penulis));
    }
}

Output:

[ab0, cd0, ef0]
[ab1, cd1, ef1]
[ab2, cd2, ef2]
[ab3, cd3, ef3]
[ab4, cd4, ef4]

You have to call new array to change the size of an array. I assume this is an exercise to practice using an array, so I'm going to avoid the classes like Arrays and System in the isiData method. You should look at those classes though.

So something like this:

public class BukuTest
{

   public String namabuku;
   public String penulis;
   public String Kategori;
   public String buku[][] = new String[ 0 ][ 3 ];

   public void isiData( String kategori, String buku, String penulis )
   {
      String[][] temp = this.buku;
      final int len = temp.length;
      this.buku = new String[ len + 1 ][];
      for( int i = 0; i < len; i++ )
         this.buku[i] = temp[i];
      this.buku[len] = new String[ 3 ];
      this.buku[len][0] = kategori;
      this.buku[len][1] = buku;
      this.buku[len][2] = penulis;
      // not needed
      // arraysize++;
      // a++;
   }
   public static void main(String[] args) {
      BukuTest b = new BukuTest();
      b.isiData( "test1", "test2", "test3" );
      b.isiData( "test4", "test5", "test6" );
      b.isiData( "test7", "test8", "test9" );
      System.out.println(b);
   }

   @Override
   public String toString()
   {
      return "BukuTest{" + "namabuku=" + namabuku + ", penulis=" + penulis +
              ", Kategori=" + Kategori + ", buku=" + 
              Arrays.deepToString(buku) + '}';
   }

}

Using an ArrayList is definitely the way to go here as others have commented and displayed but, if you are absolutely bent on using a Two Dimensional String Array then this can be done with a custom method conveniently named redimPreserve() as I have shown below.

As @Jdman1699 had mentioned in his comment under your post, this is a very inefficient way of doing this sort of thing especially for larger arrays but since you asked, here is how it can be done:

// YOUR METHOD:
public int arraysize = 1;
public String[][] buku = new String[arraysize][3];

public void isiData(String kategori, String buka, String penulis){
    // I have renamed the buku argument for this method to buka
    // since you can not have a parameter variable named the
    // same as a Class Global variable.
    buku = redimPreserve(buku, arraysize, 3);
    buku[arraysize-1][0] = kategori;
    buku[arraysize-1][1] = buka;
    buku[arraysize-1][2] = penulis;
    arraysize++;
}

// THE redimPreserve() METHOD:
public static String[][] redimPreserve(String[][] yourArray, int newRowSize, int... newColSize) {
    int newCol = 0;
    if (newColSize.length != 0) { newCol = newColSize[0]; }
    // The first row of your supplied 2D array will always establish
    // the number of columns that will be contained within the entire
    // scope of the array. Any column value passed to this method
    // after the first row has been established is simply ignored.
    if (newRowSize > 1 && yourArray.length != 0) { newCol = yourArray[0].length; }
    if (newCol == 0 && newRowSize <= 1) {
        throw new IllegalArgumentException("\nredimPreserve() Method Error!\n"
                + "No Column dimension provided for 2D Array!\n");
    }
    if (newCol > 0 && newRowSize < 1 && yourArray.length != 0) {
       throw new IllegalArgumentException("\nredimPreserve() Method Error!\n"
               + "No Row dimension provided for 2D Array!\n");
    }
    String[][] tmp = new String[newRowSize][newCol];
    if (yourArray.length != 0) {
        for(int i = 0; i < yourArray.length; i++) {
            System.arraycopy(yourArray[i], 0, tmp[i], 0, yourArray[i].length);
        }
    }
    return tmp; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM