简体   繁体   中英

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.

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.

There is no such thing as an unknown length array. Anything that is an array (of any type) in Java has a field length .

But actually that isn't your problem; as you are not using that array that is passed to your method at all. In essence you are asking how to use arrays for an unknown size of input.

There are two answers:

  1. As BlackHatSamurei suggests, you use List<Double> numbers = new ArrayList<>() - existing classes that grow dynamically when adding additional elements [ where you use List all the time, and only when instantiating the concrete object you use the specific ArrayList implemenation ]
  2. If this is about learning: you implement your own version of List. Meaning: you create a class that uses an array to store data, and whenever you want to add more elements that your array can hold; you create a new, larger array and copy all data into that array.

ArrayList

As the others suggested, you should use a Collection , specifically a List , more specifically an ArrayList .

A plain array is of fixed length. It does not grow or shrink. To add items beyond its capacity, you create a new bigger array and copy over existing items plus the new item, finally deleting the original array. An ArrayList is backed by an array but can grow. Actually, the backing array does not actually grow, it handles the details I just mentioned on your behalf: monitors the array to detect when full, then creates a new array, copies items over.

If this is homework, your instructor may be expecting you to learn the details of this chore, in which case I gave you that answer to: Create a new array, copy items, add new item, replace original array.

To use a Collection (see Tutorial ), you need to progress past working with just primitives and use actual objects. Java has primitives to help programmers transitioning from C programming, but classes and objects is really what Java is about. The class equivalent to double primitive is Double .

List<Double> costs = new ArrayList<>();
// … get your inputs from user and add each price-item to list …
costs.add ( y );

Simplify your logic

Also, your logic is convoluted, such as defining l but never using it. I tried rewriting your code but gave up. I suggest you try smaller bites, getting one thing to work at a time, building up to your desired app. Get data-entry working for a single price item, then after that works try supporting multiple price items. That is how real programming work is done, one small piece at a time.

Tip: Use descriptive names on your variables. That will help clarify your thinking.

BigDecimal

Also, in the real world you would never use double or Double for prices or anything related to money. Both of those data types use floating-point technology which trades away accuracy for speed-of-execution. So the results are approximate, not exact, and often have extraneous digits in the far right of the decimal fraction.

For money and other areas where accuracy matters, use BigDecimal objects. Feed BigDecimal a string, not a double-value as you might have already introduced the dreaded extraneous digits. This area is another reason to learn to use objects rather than primitives.

List<BigDecimal> costs = new ArrayList<>();
…
BigDecimal bd = new BigDecimal( userInputString ) ; // Input might be: 1.23
costs.add( bd );

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