I am having problems filling an array of objects with a txt file. It seems to me that it should work, but I get all 0's printed out. Please help! I cannot write the rest of my code until I figure this out.

Also I get this error message: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 50
at ChargeAccountValidation.main(ChargeAccountValidation.java:29)"

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

/**
   
*/

public class ChargeAccountValidation
{
   public static void main(String[] args) throws IOException
   {
      final int SIZE = 50;
      int[] numbers = new int[SIZE];
      int result, searchValue;
      
      int index;
      
      // Open the file.
      File file = new File("accounts.txt");
      Scanner inputFile = new Scanner(file);
      
      for (index = 0; index < numbers.length; index++)
      {
         // Read the file contents into the array
         while (inputFile.hasNext() && index < numbers.length)
         {
            numbers[index] = inputFile.nextInt();
            index++;
         }
      System.out.println(numbers[index]);
      }
      // Close the file.
      inputFile.close();
   }
}

ACCOUNTS FILE INFO:
9219306
7569177
4256928
4364059
6221744
3176698
7187438
4484503
8937630
6389278
3933096
7342775
2877438
5426950
9982031
4654335
5045697
5034644
6989075
8314073
1613911
1335305
6196903
8449641
1545292
4906480
1336532
3124745
7122978
1800843
7934692
6551425
8461254
1559757
4192728
1025121
1417918
1751466
5200307
4082692
3509247
7145465
9860616
1128882
2396421
5390896
2311287
3545377
1886054
6429595

You have most of the correct code.

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

/**
   
*/

public class ChargeAccountValidation
{
   public static void main(String[] args) throws IOException
   {
      final int SIZE = 50;
      int[] numbers = new int[SIZE];
      int result, searchValue;
      
      int index = 0;
      
      // Open the file.
      File file = new File("accounts.txt");
      Scanner inputFile = new Scanner(file);

         while (inputFile.hasNextInt() && index < numbers.length)
         {
            numbers[index] = inputFile.nextInt();
            System.out.println(numbers[index]);
            index++;
         }

      }
      // Close the file.
      inputFile.close();
   }
}

I only changed a few things: removed the for loop, initialized the index to 0, and changed the while loop's condition from hasNext() which will match basically anything to hasNextInt() which will match only an int. Alternatively you could use a for loop to do this, but combining a while & a for makes no sense:

for (int index = 0; index < numbers.length; index++){
if (inputFile.hasNextInt()) numbers[index] = inputFile.nextInt();
}

Edited 6 Years Ago by BestJewSinceJC: n/a

This question has already been answered. Start a new discussion instead.