Results 1 to 4 of 4
  1. #1
    ile4 is offline Member
    Join Date
    Nov 2010
    Posts
    24
    Rep Power
    0

    Default Problem with a for loop

    So I have an array of integers (I'm not allowed to use the java class ArrayList) and I need a method to add a new word to my array.

    What I have at the moment is a for loop:

    Java Code:
     public void addNewInt(int i) {
            for (int a = 0; a < 100; a++) {
                if (words[a] == null) {
                    words[a] = i;
                }
            }
        }
    This is adding the integer, but obviously it's adding it to all 100 spaces (when the array is empty which it currently is).

    I want the for loop to iterate through my array until it finds an empty space, add the integer to the empty space, but then stop. How can I correct my code to do this, or am I on the wrong lines completely?

    Help much appreciated :)

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,091
    Rep Power
    20

    Default

    break;

    10 chars.

  3. #3
    jomypgeorge is offline Member
    Join Date
    May 2010
    Posts
    90
    Rep Power
    0

    Default

    public void addNewInt(int i) {
    for (int a = 0; a < 100; a++) {
    if (words[a] == null) {
    words[a] = i;
    break;
    }
    }
    }

  4. #4
    ile4 is offline Member
    Join Date
    Nov 2010
    Posts
    24
    Rep Power
    0

Similar Threads

  1. While loop problem
    By mochibon in forum New To Java
    Replies: 3
    Last Post: 04-18-2010, 08:21 PM
  2. Problem with the while loop
    By molokomesto in forum New To Java
    Replies: 4
    Last Post: 02-14-2010, 05:01 PM
  3. simple line problem / for loop problem
    By helpisontheway in forum New To Java
    Replies: 1
    Last Post: 11-17-2009, 06:12 AM
  4. Some while loop problem need help
    By shaggyoo7 in forum New To Java
    Replies: 4
    Last Post: 01-14-2009, 07:16 PM
  5. Loop Problem
    By jralexander in forum New To Java
    Replies: 4
    Last Post: 12-02-2008, 07:08 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •