javadrjava

Inserting data into unknown length array java


I am making a program for a receipt maker and the array length is unknown due to multiple items. This is the code I have:

public static void main (String str[]) throws IOException {
    Scanner scan = new Scanner (System.in);
    //Entering Input
    int mult = 1;
    double price = 0;
    double y = 0;
    int l = 1;
    double [] list = new double[l];
    while(mult != 0){
      if (mult != 0)
        System.out.println("Please Enter the Cost of the Item: ");
        y = scan.nextDouble();
        list[l]= y;
        l++;
      System.out.println("More than one item? (1 = yes 0 = no) ");
      mult = scan.nextInt();
      if (mult != 0)
        price += y;
    }

and when I run it I enter the cost of the item and get an error.


Solution

  • If I were you, I would use an array list. It is a dynamic data structure that you can use, rather than a typical array where you have to define the number of elements. You can do something like:

    ArrayList<Double list = new ArrayList<Double>();
    list.add(y); 
    

    Then you get elements by doing list.get(1) or what ever element you want.

    Doing something like this will prevent you from having to know exactly how many elements you need when you declare your array.