I have a list that looks similar to thisand is stored in a text file;

last, first, code
smith, john, test

I cannot figure out why it is out of bounds. Where am I going wrong? is it in the split statement?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Scanner;

    public class FileHandling {
    static String[] className;
    static String[][] classList;
    static int counter = 0;

    public static void main(String args[]){

        className = new String[100];

        try{
        FileInputStream fstream = new FileInputStream("classNames.txt");
        DataInputStream in = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(new InputStreamReader(in));
          String strLine;
          while ((strLine = br.readLine()) != null)   {
              className[counter]=strLine;
              counter+=1;
          }
          in.close();
    }catch (Exception e){//Catch exception if any
        System.err.println("Error: " + e.getMessage());
    }//end try/catch

    int i=0;
    int num=0;
    classList = new String[100][4];
    while(num<counter){
        while (i<3){
        String tempData[] = className[num].split("(?<!\\\\),"); 
        classList[num][i]=tempData[i];
        i+=1;
        }
        i=0;
        num+=1;
    }//end while

menuSelect();
}//end method

Please post the full text of the error message.

Be sure to call the printStackTrace() method in the catch block to get the full text of the error message.

Edited 4 Years Ago by NormR1

OutOfBounds is usually if you have faulty logic in a loop that's retrieving info from, or storing data in an array.

int[] x = new int[5];
x[5] = 3;

will give you an ArrayIndexOutOfBoundsException, since there is no element with index 5.

Thanks for the help it was an error in the text document that was provided to me. Although I do have a new problem in my addStudent() method hown below;

    public static void addStudent(){
        System.out.println("How many students would you like to add?");
        Scanner input = new Scanner(System.in);
        int numberToAdd = input.nextInt();
        int x=0;
        while(x<numberToAdd){
            System.out.println("Getting data for student "+ x);
            System.out.println("What is the students first name?");
            Scanner fnInput = new Scanner(System.in);
            String FirstName = fnInput.next();
            FirstName = FirstName.toString();

            System.out.println("What is the students last name?");
            Scanner lnInput = new Scanner(System.in);
            String LastName = lnInput.next();
            LastName = LastName.toString();

            System.out.println("What course is the student in?");
            Scanner courseInput = new Scanner(System.in);
            String course = courseInput.next();
            course = course.toString();

            classList[counter+x][0]=FirstName;
            classList[counter+x][1]=LastName;
            classList[counter+x][2]=course;
            x+=1;
        }//end while
        counter+=numberToAdd;

        try{
              // Create file 
              FileWriter fstream = new FileWriter("classNames.txt");
              BufferedWriter out = new BufferedWriter(fstream);
              int num=0;
              int i=0;
              while (num<counter){
                    while (i<1){
                        className[num]=(classList[num][i]+","+classList[num][i+1]+","+classList[num][i+2]);
                        i+=1;
                    }//end while
                    num+=1;
                    i=0;
                }//end while
                Arrays.sort(className);//problem here
                num=0;
                    while (num<counter){
                        out.write(className[num]);
                        out.newLine();
                        num+=1;
                    }
              out.close();            //Close the output stream
              }catch (Exception e){//Catch exception if any
              }//end try/catch
    }//end method

The program works fine when i get rid of the sort function however when I use the sort function the program outputs a blank text document. Any help is great.

What are the values of num and counter when the code is writing to the file? Print them out to see.
What is in the className array? Print out its contents using Arrays toString() method to format the array for printing.

Add a call to printStackTrace() in the catch block at line 52 to show any errors that could be happening. Your code is ignoring them.

I followed all of you tips and found no problems in the num or counter variable. I printed the class array and it has elements in all the positions so it does not make sense that I was getting a nullpointerexception in the error output. Any other tips for why it may be getting the null pointer exception?

Are you now getting a nullpointerexception? If so, please post the full text of the error message.

this is the full error that I am receiving

exception: null
java.lang.NullPointerException
at java.lang.String.compareTo(Unknown Source)
at java.lang.String.compareTo(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at FileHandling.addStudent(FileHandling.java:130)
at FileHandling.menuSelect(FileHandling.java:58)
at FileHandling.main(FileHandling.java:42)

What variable has a null value on line 130?
Are any of the elements in the className array null?

Edited 4 Years Ago by NormR1

Thanks, there was some null elements that were tacked on to the end of the array.

I printed the class array and it has elements in all the positions

there was some null elements that were tacked on to the end of the array.

The compareTo method will throw a NPE with null elements.

Edited 4 Years Ago by NormR1

I set it up so that the all the null elements are removed however there is an issue i the showClass() method where it says the value of the first element is null however there are no null elements in the array as far as I can tell.

Full error:
Exception in thread "main" java.lang.NullPointerException
at FileHandling.showClass(FileHandling.java:72)
at FileHandling.menuSelect(FileHandling.java:44)
at FileHandling.main(FileHandling.java:38)

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


    public class FileHandling {
    static String[] className;
    static int counter = 0;

    public static void main(String args[]){
        String[] classList = new String[100];

        try{
        FileInputStream fstream = new FileInputStream("classNames.txt");
        DataInputStream in = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(new InputStreamReader(in));
          String strLine;
          while ((strLine = br.readLine()) != null)   {
              classList[counter]=strLine;
              counter+=1;
          }
          int i = 0;
          String string = "string";
          String[] className = new String[counter];
          while (string.length() != 0){
              string = classList[i];
              System.out.println(string);
              className[i]=string;
              System.out.println(className[i]);
              i+=1;
          }

          Arrays.sort(className);
          in.close();
    }catch (Exception e){//Catch exception if any

    }//end try/catch

menuSelect();
}//end method


    public static void menuSelect(){
        while (true){
            showClass();
            System.out.println("\nDo you want to:\n" +
                "(A)dd a user to the file.\n" +
                "(E)dit a user from the file.\n" +
                "(D)elete a user from the file.\n" +
                "E(X)it");
            Scanner input = new Scanner(System.in);
            String menuSelection = input.next();
            menuSelection = menuSelection.toString();
            if (menuSelection.equals("A")){
                addStudent();
            }else if(menuSelection.equals("E")){
                //editStudent
            }else if(menuSelection.equals("D")){
                //deleteStudent()
            }else if(menuSelection.equals("X")){
                break;
            }else{
                System.out.println("That is not a valid letter.\n");
            }
        }//end while
    }//end menuSelect


    public static void showClass(){
        int i=0;
        System.out.println("\n\n\n\n\nLast Name, First Name, Course");
            while (i<counter){
                System.out.println(className[i]);
                i+=1;
            }//end while
    }//end showClass

    public static void addStudent(){
        System.out.println("How many students would you like to add?");
        Scanner input = new Scanner(System.in);
        int numberToAdd = input.nextInt();
        int x=0;
        while(x<numberToAdd){
            System.out.println("Getting data for student "+ x+1);
            System.out.println("What is the students first name?");
            Scanner fnInput = new Scanner(System.in);
            String FirstName = fnInput.next();
            FirstName = FirstName.toString();

            System.out.println("What is the students last name?");
            Scanner lnInput = new Scanner(System.in);
            String LastName = lnInput.next();
            LastName = LastName.toString();

            System.out.println("What course is the student in?");
            Scanner courseInput = new Scanner(System.in);
            String course = courseInput.next();
            course = course.toString();

            String stringInput=LastName+", "+FirstName+", "+course;
            className[counter] = stringInput;



            x+=1;
        }//end while
        counter+=numberToAdd;

        try{
              // Create file 
              FileWriter fstream = new FileWriter("classNames.txt");
              BufferedWriter out = new BufferedWriter(fstream);
              int num=0;

                Arrays.sort(className);
                num=0;
                    while (num<counter-1){
                        System.out.println("num="+num+" counter="+counter);
                        System.out.println(className[num]);
                        out.write(className[num]);
                        out.newLine();
                        num+=1;
                    }
              out.close();            //Close the output stream
              }catch (Exception e){//Catch exception if any
                     System.out.println("exception: " + e.getMessage());
                     e.printStackTrace();

              }//end try/catch
    }//end method
}//end class

Printing an element with a null value should NOT cause a NPE,
What is the value of className? Print it out to see if that is null.

Edited 4 Years Ago by NormR1

On line 6 you declare, but do not initialise an array variable called className, so its initial value is null. That's the one you try to use on line 72, which is why you get an NPE.

Your code on lines 24-29 has absolutely no effect on this because that is populating a local variable, also called className, that is declared and initialised on line 23 and is local to the main method.

As I understand it, that's not an error (although it may be a vary bad idea). The JLS says

If a name declared as a local variable is already declared as a field name, then that outer declaration is shadowed (ยง6.3.1) throughout the scope of the local variable.

It's legal code but I can not see when it is ever desired. The IDE should issue a warning.
With other languages that have a source code include feature you could shadow a class variable to keep the included code from getting to a class variable. Not an argument for java.

I agree. Eclipse has an option to flag local variable names that shadow a field, but I can't speak for other IDEs.
I've seen far too many problems on DaniWeb caused by exactly this mistake.

Thanks I did'nt realise line 25 was over writing the global array.

This article has been dead for over six months. Start a new discussion instead.