Too many loops?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ronparker
    New Member
    • Aug 2010
    • 27

    Too many loops?

    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?

    Code:
    for (int n = 1; n < 100; n++) {
         Variable1 += Array1.get(Array1.size() - n);
    
    for (int j = 1; j < 40; j++) {
         Variable2 += Array2.get(Array2.size() - j);
    
    for (int l = 1; l < 93; l++) {
         Variable3 += Array3.get(Array3.size() - l);
    Thank you in advance for anyone that can help out with this
    Last edited by Niheel; Apr 9 '12, 07:05 PM.
  • RemalKoil
    New Member
    • Apr 2012
    • 1

    #2
    You can try with a function like:
    Code:
    public int addLast(int amount, List array, int initialValue) {
        for (int i = 1; i <= amount; ++i) {
             initialValue += array.get(array.size() - i);
        }
        return initialValue;
    }
    usage:

    Code:
       Variable1 = addLast(100, Array1, Variable1);
       Variable2 = addLast(40, Array2, Variable2);
       Variable3 = addLast(93, Array3, Variable3);

    Comment

    Working...