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 );