Asia x3
Asia x3

Reputation: 616

Reading from a file using a Scanner and a method

I'm having big trouble with figuring out how to read from a file using a scanner and method. Here's my outline I have:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class ReadFile1 {
    public static void main(String[] commandlineArgument) {
        Integer[] array = ReadFile1.readFileReturnIntegers(commandlineArgument[0]);
        ReadFile1.printArrayAndIntegerCount(array, commandlineArgument[0]);
    }

    public static Integer[] readFileReturnIntegers(String filename) {
        Integer[] array = new Integer[1000];
        //...?
        return array;
    }

    public static void printArrayAndIntegerCount(Integer[] array, String filename) {
        //...?
    }
}

I'm trying to read and return an array integers with all and only the integers from my inputted file. I'm so confused with how these methods work and I have no clue on how to start reading.

Sample Output:

    index = 0, element = 1877
    index = 1, element = 1879
    index = 2, element = 2000

Upvotes: 0

Views: 176

Answers (1)

Grmpfhmbl
Grmpfhmbl

Reputation: 1147

Have you read the API-Docs for the java.util.Scanner class? They have some short examples. I'm just assuming your ints are delimited by whitespaces. I would rather use Lists, as you normally wouldn't know how many integers are in your file. You can use List.toArray() later if you really want to have an array.

Just another question, why to you pass a filename to your read function, when you created a Scanner instance before?

public static Integer[] readFileReturnIntegers(Scanner sc) {
    List<Integer> list = new ArrayList<Integer>();
    while (sc.hasNextInt()) {
        list.add(sc.nextInt());
    }
    return list.toArray(new Integer[list.size()]);
}

For outputting your array I'd just use java.io.PrintWriter. My example function so far does not do any sanity checks like checking for existing file etc. And just for the ease of reading I used the Java7 try-with-resources Statement syntax. If you still use Java 6 you have to rewrite the try / catch a little. See this thread for example

public static void printArrayAndIntegerCount(Integer[] array, String filename) {
    try (PrintWriter pw = new PrintWriter(filename);) {
        pw.println("number of integers in file \"" + filename+ "\" = " + array.length);
        for (int i=0; i<array.length; i++) {
            pw.println("    index = " + i + "; element = " + array[i]);
        }
    }
    catch (Exception e) {
        //handle exceptions
    }
}

Upvotes: 1

Related Questions