Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how do you fix this error when trying to initialize an arraylist?

for my partial code below i am trying to read a txt file into an array list, however I keep getting this error when trying to run my code.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

if you could please explain how to go about fixing this that would be great, the internet say its due to the fact that my arraylist is not initialized correctly.
this is my partial code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

class Nonsense
{
   public int numbLines = 10000;
   public ArrayList<String> line = new ArrayList<String>();
   
   public static void main (String [] args)
   {
      int x = Integer.valueOf(args[0]); //convert from string to int
      // populate arrayList from file 
      // shuffle the array
      // save to file   
   }  
     
      public void readInFile ()
      {
      try {
         Scanner sc = new Scanner (new File("nonsense.txt"));
         while (sc.hasNextLine ())
            {
            String currentLine = sc.nextLine();
            line.add(currentLine);
            }
       }catch (Exception e){
            System.out.println("File not found");
         }
      }
 
         

>Solution :

You are trying to access the value of non-existing args Array in

int x = Integer.valueOf(args[0]);

How do you fix that? If args is still what you want to use, then you could try to check if args even exists by checking its length.

public static void main(String[] args)
{
    // Check how many arguments were passed in
    if(args.length == 0)
    {
        System.out.println("Empty args.");
        System.exit(0);
    }
    
    int x = Integer.valueOf(args[0]); //convert from string to int
    // populate arrayList from file 
    // shuffle the array
    // save to file 

}

EDIT

args Array of course exists. It is just empty(it has no values). That’s what you should be checking.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading