The Artima Developer Community
Sponsored Link

Java Answers Forum
Arrays - add selected elements

1 reply on 1 page. Most recent reply: Jun 20, 2005 12:27 AM by Matthias Neumair

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Wendi

Posts: 1
Nickname: wendi
Registered: Jun, 2005

Arrays - add selected elements Posted: Jun 17, 2005 6:58 AM
Reply to this message Reply
Advertisement
I have a program where item names, prices are part of separate arrays. The user inputs the items they want and the quantity they want. I then need to add the elements (only the ones that the user has selected from input) and output them. My code (below) sums the prices of all the elements in the aray. how would I get it to just add the ones the user input (which would be different every time)

double sum=0;
for(double i=0;i<Price.length;i++)
{ sum = sum+Price[row]; }


Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: Arrays - add selected elements Posted: Jun 20, 2005 12:27 AM
Reply to this message Reply
1st of all: the names of varables including arrays should be small.
Only classes shoukd begin with a capital letter.

Now to your problem

I suppose you have the followig structure:

double price[n];
int quantity[n];

I don't have the minimum idea how your code can add all prices.
Id looks to me as if after this lines
sum = Price[row] * Price.length;
because you never alter row.


Try this:

double sum = 0;
for (int i = 0; i < price.length; i++) {
if (quantity[i] > 0)
sum = sum+price[i];
}

Note that this way it is only checked IF there is a quantity, but not what the quantity is.

Flat View: This topic has 1 reply on 1 page
Topic: Setting Image as Background for JFrame. Previous Topic   Next Topic Topic: Question about button action in a gui

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use