Results 1 to 4 of 4
  1. #1
    randoms:) is offline Member
    Join Date
    Apr 2011
    Location
    Glasgow
    Posts
    5
    Rep Power
    0

    Default read input file into array

    I am trying to put the contents of an input file into an array. I have searched online and the only examples I can find are for arrayLists. I cant use an arrayList for this example. I would really appreciate your help!! Thanks
    Last edited by randoms:); 04-22-2011 at 10:49 PM.

  2. #2
    farahm is offline Member
    Join Date
    Nov 2010
    Location
    Beirut, Lebanon
    Posts
    36
    Rep Power
    0

    Default

    The following code I wrote enables you to read input from a file into an array:
    Java Code:
    import java.util.*; 
    import java.io.*; 
    
    public class example3
    {
        public static void main (String args[]) throws FileNotFoundException 
        {
            Scanner scan = new Scanner(new File(args[0])); //provide file name from outside
            int counter =0; //keep track of how many integers in the file
            while(scan.hasNextInt()) 
            {
                counter++;
                scan.nextInt();
            }
            Scanner scan2 = new Scanner(new File(args[0])); 
            int a[] = new int[counter];
            for(int i=0;i<counter;i++)
            {
                a[i]=scan2.nextInt(); //fill the array with the integers
            }
        }
    }
    I tried the code on an input file and it worked.

  3. #3
    randoms:) is offline Member
    Join Date
    Apr 2011
    Location
    Glasgow
    Posts
    5
    Rep Power
    0

    Default

    Thank you very much :)

  4. #4
    farahm is offline Member
    Join Date
    Nov 2010
    Location
    Beirut, Lebanon
    Posts
    36
    Rep Power
    0

Similar Threads

  1. Read user input into integer array
    By varunb in forum New To Java
    Replies: 12
    Last Post: 07-09-2010, 12:50 PM
  2. read only double input from text file
    By napi1234 in forum New To Java
    Replies: 6
    Last Post: 06-28-2010, 04:06 PM
  3. Read File into 2d array
    By almjodla in forum New To Java
    Replies: 8
    Last Post: 03-23-2010, 02:55 PM
  4. file input: array of integers
    By hannes in forum New To Java
    Replies: 8
    Last Post: 01-27-2010, 03:44 PM
  5. read a specific line in an input file
    By sara12345 in forum Advanced Java
    Replies: 7
    Last Post: 01-03-2010, 10:40 PM

Tags for this Thread

Posting Permissions

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