1

I create a ProductMenu class to perform the add, search, delete and update product tasks and it only use the array. What problem that i face is how to add static variable in a method because i failed to add the maximum number of array after add a product into array. Hope can help and thank you.

public static void addProduct(){

    Product product = new Product();
        System.out.println("================================");
        System.out.println("           Add Product          ");
    System.out.println("================================");
    System.out.println("Product ID :- " + Product.getProdId());
    System.out.print("Enter product name: ");
    String prodName = input.next();
    System.out.print("Enter product price: ");
    double prodPrice = input.nextDouble();
    product.setProductId(Product.getProdId());
    product.setProductName(prodName);
    product.setProductPrice((double)prodPrice);

    products[productIndex] = product;
    numOfArray++; // should be add ?
    productIndex++; // should be add also?

    ProductMenu.main(null); //back to main


}

My class

 public class ProductMenu {

  static Scanner input = new Scanner(System.in);
   static int productIndex; //should be add after addProduct()
    static int numOfArray = 1; //should be add after addProduct()
static Product[] products = new Product[numOfArray];

public static void main(String[] args) {

    int menuOption;

    do{

    menu();
    System.out.print("Enter your choice: ");
    menuOption = input.nextInt();

    switch(menuOption){
        case 1:
            addProduct();
            break;
        case 2:
            System.out.print("halo" + products[0].toString());
            break;
        case 3:

            break;
        case 4:

            break;
        default:

            System.out.print("Invalid option. Please try 
                    again.\n");
            break;
    }

    }while(menuOption!=1 && menuOption!=2 && menuOption!=3 && 
      menuOption!=4 );

}

    public static void menu(){
        System.out.println("================================");
        System.out.println("          Product Menu         ");
    System.out.println("================================");
    System.out.println("1. Insert Product\n2. Update Product\n3. 
        Search Product\n4. Delete Product\n");
}

This is error msg that mean array number already more than limit and why i ask if i not wrong.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at ProductMenu.addProduct(ProductMenu.java:64)
at ProductMenu.main(ProductMenu.java:21)
at ProductMenu.addProduct(ProductMenu.java:68)
at ProductMenu.main(ProductMenu.java:21)
ZT Chuah
  • 9
  • 6
  • 1
    Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Sharon Ben Asher Jul 28 '19 at 08:41
  • Thank for reply and i know array index is start from 0. In my code numOfArray is mean how many array index of that array and default is 1 which index 0. And in my addProduct() function after i add the product into array , that numOfArray will ++ which mean will became 2 when i add another new but i get wrong which is not increase the numOfArray – ZT Chuah Jul 28 '19 at 08:50
  • Use ```java.util.ArrayList``` instead of using ```Array``` for dynamic size. – Nitin Zadage Jul 28 '19 at 08:52
  • Did the Array really cannot dynamic change the size with the code? – ZT Chuah Jul 28 '19 at 08:58
  • An array once created cannot change size. – Mark Rotteveel Jul 29 '19 at 15:51

3 Answers3

0

I was wondering whether you could replace array with arraylist in your code. Arraylists are backed by arrays in background and you need not worry about arrayindexoutofbound exception while handling the data

Kavitha Karunakaran
  • 1,340
  • 1
  • 17
  • 32
  • Thank for reply but i still want to use array and how i can solved this problem? – ZT Chuah Jul 28 '19 at 08:53
  • You need to create a new array say new prodArr with length = product.length+1, create a for loop and add all contents of product[] to it and add new product to prodArr[prodArr.length -1]. Then make product= prodArr. This needs to be done each time new product is added. I would say that is too much of and overkill. – Kavitha Karunakaran Jul 28 '19 at 08:59
  • Oops.. This is so trouble – ZT Chuah Jul 28 '19 at 09:15
  • Hence it is better to use java.util.Arraylist. afterall, why should one reinvent the wheel? :) – Kavitha Karunakaran Jul 28 '19 at 09:19
0

To your problem: I would use an ArrayList or a LinkedList because it has a dynamic size. The size of an array cannot be changed after initialization and yours is set to 1. That will cause problems.

Addition: You do not need to call ProductMenu.main(null); //back to main because your addProduct function is called in the main method and after executing your function your program will continue in the main function.

cid
  • 15
  • 6
  • Thank for reply. But if i not call ProductMenu.main(null); , it not continue in the main function and just output process completed and finished. And array cannot use the code for dynamic change? – ZT Chuah Jul 28 '19 at 08:57
  • An array has a fixed size so if you want your product list to have a maximum number of products you set your array size e.g. to 10: ```static Product[] products = new Product[10];``` But then your program will crash if you add more than 10 elements. If you want no limit of elements you have to use some kind of List like ```java.util.ArrayList``` – cid Jul 28 '19 at 09:01
  • It's bad practice to call your main function in the addProduct function because it will cause recursion. The reason your program ends after adding a product is your while loop condition. Replace it with: ```while(menuOption==1 || menuOption==2 || menuOption==3 || menuOption==4);``` – cid Jul 28 '19 at 09:06
  • but if i replace with while(menuOption==1 || menuOption==2 || menuOption==3 || menuOption==4); when i enter another num like 9 it will not reloop to the main function and just process finished – ZT Chuah Jul 28 '19 at 09:16
  • So you want to run all the time? Then try something like this: while(menuOption != -1); This will continue the loop until you type -1 to exit your program. – cid Jul 28 '19 at 09:25
0

As you need to use Array only then create one function add() which will first check size of array, if there is space left then add element else create new array of double size , copy all previous elements and add new one at end. Also as size is static variable you don't have to pass to your method. Your method is also static and both method and variable in same class so you can directly use variable in method.

Tejas
  • 276
  • 2
  • 8
  • If you want me to create than function let me know. Happy to help – Tejas Jul 28 '19 at 08:59
  • Thank for reply. Are you mean that i have to create a new function to check that if array size is not enough to keep the value ,than add the array size and copy the another array that keep the value before to a new array then replace the array that keep the value before? – ZT Chuah Jul 28 '19 at 09:12
  • sorry but i didnt understand your reply. Let me explain with example. e.g. we have array 'first' with initial size of 10. If we want to add any element , add() function will check size of array . If it is less than 10 , it will add element in it and return array. Consider scenario , that if we try to add 11th element in array, then add() function will first check and realize 'first' array has come to its limit so it will create new array 'second' of size double that of current array and add 11th element into it. Then return this 'second' array. You can write like first = add(first). – Tejas Aug 13 '19 at 17:34