simple java question

Discussion in 'OT Technology' started by Rommel, Mar 6, 2003.

  1. Rommel

    Rommel friends forever

    Joined:
    Jul 31, 2001
    Messages:
    36,867
    Likes Received:
    0
    Location:
    /yourself now
    public class MoFo
    {
    public static void main(String[] args)
    {
    int[] array = new int[3];
    array[0] = 4;
    array[1] = 4;
    array[2] = 2;


    int sum = 0;

    for(int i = 0; i <=array.length; )
    {
    sum = 0;
    sum += array[i++];
    }
    System.out.println(sum);

    }

    }

    this is giving me a index.out of bounds error

    can someone please tell me why

    i am a serious newb for java so anything is appreciated
     
  2. CompiledMonkey

    CompiledMonkey New Member

    Joined:
    Oct 26, 2001
    Messages:
    8,528
    Likes Received:
    0
    Location:
    Richmond, VA
    I assume you're looking to see sum print out as 10. Is that right? Just let me know your goal and I'll help out.
     
  3. CompiledMonkey

    CompiledMonkey New Member

    Joined:
    Oct 26, 2001
    Messages:
    8,528
    Likes Received:
    0
    Location:
    Richmond, VA
    I'll just assume you are going for that. :)

    1. You should create an ArrayList object (java.util.ArrayList) for this task.

    2. Your for loop isn't being used properly. The increment (i++) should take place in your statement, not the block of code being looped.

    3. Each time your loop executed, you are setting the sum back to zero. So it will only show the value of the last array address it hits.

    Here's what I came up with:

    Code:
    import java.util.ArrayList;
    
    public class MoFo {
    
      public static void main(String[] args) {
        ArrayList array = new ArrayList(3);
        array.add(0, "4");
        array.add(1, "4");
        array.add(2, "2");
    
        int sum = 0;
    
        for(int i = 0; i < array.size(); i++) {
          sum += Integer.parseInt((String)array.get(i));
        }
    
        System.out.println(sum);
      }
    }
    
     
  4. Rommel

    Rommel friends forever

    Joined:
    Jul 31, 2001
    Messages:
    36,867
    Likes Received:
    0
    Location:
    /yourself now
    got it sorted, thanks anyway, cant beleive it was just the less athan or equal to function screwing up the whole loop

    also initialising the sum as 0 in every itteration was a bad idea on my part

    thanks anyway:)
     
  5. Rommel

    Rommel friends forever

    Joined:
    Jul 31, 2001
    Messages:
    36,867
    Likes Received:
    0
    Location:
    /yourself now
    wish i learnt all this last semester
     

Share This Page