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:
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.