File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Adding arrays? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Adding arrays?" Watch "Adding arrays?" New topic
Author

Adding arrays?

karina val
Greenhorn

Joined: Sep 02, 2011
Posts: 6
I have 3 arrays that were filled from a file. The first column is breakfast, the second column is lunch, and the third column is dinner. But now I have to get the totals for each day (or row), and I don't know how to do that without having a multi dimensional array since I already have 3 arrays filled.
The file looks like this, the numbers correspond to calories, each row is a day:
200 1000 800
450 845 1200
800 250 400
0 1500 1800
600 500 1000
700 1400 1700
675 400 900

I'm not asking for a code, just a suggestion or idea how to get around this :S I know how to add rows and columns in 2d arrays but this threw me off.

karina val
Greenhorn

Joined: Sep 02, 2011
Posts: 6
So I got the sum for the first row using this... haha

int first = 0;
int sum = 0;

sum += breakfast[first] + lunch[first] + dinner[first];
System.out.println(sum);

but how could I get so it goes through the rest of the indexes without retyping or copying and pasting the code 7 times...?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19655
    
  18

Use a for-loop.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Patrick Noah
Greenhorn

Joined: Aug 22, 2011
Posts: 28
Calculate a daily total for say, day 0. iterate through the days and have the calculation for the daily total in the loop.
karina val
Greenhorn

Joined: Sep 02, 2011
Posts: 6
I got it! Thanks


Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19655
    
  18

Why don't you replace day with your loop variable i?

Oh, and welcome to the Ranch!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38045
    
  22
karina val wrote: . . .
int sum = 0;

sum += breakfast[first] + lunch[first] + dinner[first]; . . .
Like many beginners, you have some unnecessary code. You mean int sum = breakfast[first] + lunch[first] + tea[first];
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38045
    
  22
Rob Spoor wrote:Why don't you replace day with your loop variable i? . . .
As I said earlier, you have some unnecessary lines.
 
 
subject: Adding arrays?
 
Similar Threads
Adding 2-d ArrayList to JTable
loops that slow down
Function not returning values.
Passing Parameters between classes
method takes longer each time