2

Say i have a file called "input.txt" that has a bunch of positive integers in it:

6
5
6
8
6
2
4

and so on....(one integer per line)

I want to read this file and make it into an array. The first integer (in this case 6) tells the number of indexes or elements in the array, so 6 spots. The other numbers fill in the array starting at 0. So at index 0, the number is 5, at index 1 the number is 6, and so on.

Can someone please show me how to read this file and make it into an array called A and return the integers in each index as n?

this is what i have so far:

import java.io.*;
public class inputFile {
    public static jobScheduleRecursive(int[] A, int i)
    {
        try
    {
        FileReader filereader = new FileReader("input.txt");
        BufferedReader bufferedreader = new BufferedReader(filereader);
        String line = bufferedreader.readLine();
        //While we have read in a valid line
        while (line != null) {
            //Try to parse integer from the String line
            try {
                System.out.println(Integer.parseInt(line));
            } catch (NumberFormatException nfe) {
                System.err.println("Failed to parse integer from line:" + line);
                System.err.println(nfe.getMessage());
                System.exit(1);
            }
            line = bufferedreader.readLine();
        }
    }
    catch(FileNotFoundException filenotfoundexception)
    {
        System.out.println("File not found.");
    }
    catch(IOException ioexception)
    {
        System.out.println("File input error occured!");
        ioexception.printStackTrace();
    }
    return A;
}
2
  • 1
    We're not going to do your work for you. What have you tried? Post your current code, and we can help you correct it. Commented Oct 9, 2011 at 3:54
  • 4
    homework? what have you tried so far? Commented Oct 9, 2011 at 3:55

1 Answer 1

5

Step by step (I will let you fill in the actual code):

  1. read the first integer (the java.util.Scanner can be used to read the next integer) into a variable (let's call it numberOfInts)
  2. Create an array called A with numberOfInts elements
  3. In a loop, counting from 0 to numberOfInts - 1 (using index variable i):
    • read the next integer from the file
    • set A[i] to be that integer you just read

Here are some references:

http://download.oracle.com/javase/1,5,0/docs/api/java/util/Scanner.html

http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.