| Author |
Performing math equations within arrays
|
Julie Nelson
Greenhorn
Joined: Nov 24, 2008
Posts: 13
|
|
Can someone point me in the right direction on this...I'm just now learning arrays and am trying to figure out how to get a sum or difference of my array numbers. So far I can display all the numbers but is there a different way to perform math when it comes to arrays, different from plugging in floating point variables?
public class Merchandise
{
public static void main(String[] args)
{
double[] salary = {5.25, 6.55, 10.25, 16.85};
System.out.println("Salaries one by one are:");
for(int x = 0; x < salary.length; ++x)
System.out.println(salary[x]);
}
}
|
 |
Christophe Verré
Sheriff
Joined: Nov 24, 2005
Posts: 14672
|
|
|
Do you know how to make a sum or difference of two variables ? If you can, doing it with arrays is not different, if you consider that things in the array are variables too.
|
[My Blog]
All roads lead to JavaRanch
|
 |
Julie Nelson
Greenhorn
Joined: Nov 24, 2008
Posts: 13
|
|
So if I want to add 5.25 to 6.55 will I type the following?
int value1 = 5.25, value2 = 6.55;
sum = value1 + value2;
System.out.println("Sum is " + sum);
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16692
|
|
Julie Nelson wrote:So if I want to add 5.25 to 6.55 will I type the following?
int value1 = 5.25, value2 = 6.55;
sum = value1 + value2;
System.out.println("Sum is " + sum);
Yes, but that's not using arrays -- what Christophe is saying is that elements of the array are just like any other variable...
double[] salary = {5.25, 6.55, 10.25, 16.85};
sum = salary[0] + salary[1];
System.out.println("Sum is " + sum);
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Julie Nelson
Greenhorn
Joined: Nov 24, 2008
Posts: 13
|
|
|
So I guess I have to make a separate array for the "sum"?
|
 |
Christophe Verré
Sheriff
Joined: Nov 24, 2005
Posts: 14672
|
|
So I guess I have to make a separate array for the "sum"?
Why not using a single variable ?
|
 |
Julie Nelson
Greenhorn
Joined: Nov 24, 2008
Posts: 13
|
|
|
Thank you both for your help!!! I really appreciate it.
|
 |
 |
|
|
subject: Performing math equations within arrays
|
|
|