robertparsons4
robertparsons4

Reputation: 81

Array contains only zeros when creating an integer array from a file in Java?

So this program needs to be able to receive a text file containing a line of text and various lines of integers and store them in separate arrays. Here's a text file sample:

five hexing wizard bots jump quickly
21 5 6 11 15 9 10 3 34 22 28 5 15 2 3 4 21 5 3 18 27 5 20 9 6 23 19 20 7

I've figured out how to store the text into a character array, and I've figured out how to set up an integer array to accept the integers in the text file. However, whenever I try to print the array, it's filled with zeros and not with the numbers contained in the text file. Here is my code so far (the code that copies the integers from the text file into the array is at the bottom of the program):

import java.util.*;
import java.io.*;

public class Decoder 
{
public static void main(String[] args) throws IOException
{
    Scanner keyboard = new Scanner(System.in);
    String fileName;

    System.out.println("Please enter the name of a file to be decoded: ");
    fileName = keyboard.nextLine();

    File testFile = new File(fileName);
    Scanner inputFile = new Scanner(testFile);

    String keyPhrase = inputFile.nextLine();

    char[] letterArray = new char[keyPhrase.length()];
    letterArray = keyPhrase.toCharArray();

    int counter = 0;
    while(inputFile.hasNextInt())
    {
        counter++;
        inputFile.nextInt();
    }

    int[] numArray = new int[counter];

    int i = 0;
    while(inputFile.hasNextInt())
    {
        numArray[i++] = inputFile.nextInt();
    }

    System.out.println(Arrays.toString(numArray));
}

The answer is probably very simple (I'm new to Java and programming in general), but any help would be appreciated!

Upvotes: 0

Views: 539

Answers (1)

Alex Taylor
Alex Taylor

Reputation: 8853

You're reading the line with integers twice - ignoring them all the first time. This chunk reads and ignores all the numbers (to know how big the array needs to be):

int counter = 0;
while(inputFile.hasNextInt())
{
    counter++;
    inputFile.nextInt();
}

Then this chunk tries to read more integers but they've already been read:

int i = 0;
while(inputFile.hasNextInt())
{
    numArray[i++] = inputFile.nextInt();
}

Try using an ArrayList. They will dynamically grow as you add more things to them:

ArrayList<Integer> numbers = new ArrayList<Integer>();
while(inputFile.hasNextInt())
{
    numbers.add(inputFile.nextInt());
}

You can then use one of the two toArray methods if you specifically need an array. The other alternative is to scan your file twice - once to get the length of the array, then again to actually load the numbers.

Upvotes: 1

Related Questions