By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,651 Members | 1,316 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,651 IT Pros & Developers. It's quick & easy.

Too many loops?

P: 27
Hello All!
I would greatly appriciate some help given I'm just starting out in Java. I have written a pice of code which includes a lot of "for" statments (a few of them are called below). Since they are essentially doing the same thing, (Adding the last X elements of different arrays to a different variable) would it be possible to simplfy this into a process that keeps getting called instead of writting a new for loop everytime i want to do this?

Expand|Select|Wrap|Line Numbers
  1. for (int n = 1; n < 100; n++) {
  2.      Variable1 += Array1.get(Array1.size() - n);
  3.  
  4. for (int j = 1; j < 40; j++) {
  5.      Variable2 += Array2.get(Array2.size() - j);
  6.  
  7. for (int l = 1; l < 93; l++) {
  8.      Variable3 += Array3.get(Array3.size() - l);
  9.  
  10.  
Thank you in advance for anyone that can help out with this
Apr 9 '12 #1
Share this Question
Share on Google+
1 Reply


P: 1
You can try with a function like:
Expand|Select|Wrap|Line Numbers
  1. public int addLast(int amount, List array, int initialValue) {
  2.     for (int i = 1; i <= amount; ++i) {
  3.          initialValue += array.get(array.size() - i);
  4.     }
  5.     return initialValue;
  6. }
  7.  
usage:

Expand|Select|Wrap|Line Numbers
  1.    Variable1 = addLast(100, Array1, Variable1);
  2.    Variable2 = addLast(40, Array2, Variable2);
  3.    Variable3 = addLast(93, Array3, Variable3);
  4.  
Apr 13 '12 #2

Post your reply

Sign in to post your reply or Sign up for a free account.