Forum Stats

  • 3,837,208 Users
  • 2,262,236 Discussions
  • 7,900,222 Comments

Discussions

Initializing Arrays with numbers from file

807569
807569 Member Posts: 34,691
edited May 15, 2006 10:22AM in Java Programming
How can I initialize array with numbers from file, when I don't know how many numbers are in this file?

Comments

  • 791266
    791266 Member Posts: 18,005
    Use a list instead, e.g. ArrayList or LinkedList.

    Kaj
  • 807569
    807569 Member Posts: 34,691
    But this is part of my school project. and I can't use this classes.
  • 807569
    807569 Member Posts: 34,691
    The better way is to use the list as explained earlier. Since you can't do that you can try the following methodology:
    public class NumbersFromFile
    {
      private int[] data = new int[0];
    
      public NumbersFromFile()
      {
      }
    
      public inputNumber(int num)
      {
        // Expand your array
        int[] tmp = new int[data.length + 1];
    
        // copy
        System.arraycopy(data, tmp, 0, data.length);
    
        // add your value to the end
        tmp[tmp.length - 1] = num;
    
        // swap
        data = tmp;
      }
    }
    That is the basic way to illustrate how to do it. A better way would be to use a larger size array and only copy as necessary (when it fills up) and only return the size array you need at the end.
  • 807569
    807569 Member Posts: 34,691
    Back when I was in university I generally countered this with "what is the class library for?"
This discussion has been closed.