-1

Java is throwing me an Exception (which in most cases is a solid beginner and easy-to-fix error) that I can't figure out (this is the console output):

0001
0002
0003
0004
0005
0006
0007
0008
0009
0010

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at guia3.Main.addHab(Main.java:59)
    at guia3.Main.main(Main.java:32)

Here's the code

    public static void main(String[] args) throws FileNotFoundException 
{
    ArrayList <HabitacionDoble> habDoble = new ArrayList<HabitacionDoble>();
    ArrayList <HabitacionTriple> habTriple = new ArrayList <HabitacionTriple>();
    ArrayList <Depto4Plus> deptos = new ArrayList <Depto4Plus>();
    int i;
    String linea[];
    File roomsFile = new File ("C:\\Users\\Notebook\\Guia 3\\rooms.txt");       
    //leer el archivo para test
    Scanner x = new Scanner (roomsFile);
    while (x.hasNext())
    {
        linea = x.nextLine().split(";");
        System.out.println(linea[0]);//this is just for testing purpose, trying to find where the error falls
        addHab (linea, habDoble, habTriple, deptos);

    }
x.close();



}//end main

public static void addHab (String[] linea, ArrayList<HabitacionDoble> habDoble, ArrayList<HabitacionTriple> habTriple,
        ArrayList <Depto4Plus> deptos)
{
    if (linea[1].equals("2"))
    {
        habDoble.add(new HabitacionDoble());
        habDoble.get(habDoble.size()-1).setCodigo(linea[0]);
        habDoble.get(habDoble.size()-1).queCategoria(linea[2]);
        habDoble.get(habDoble.size()-1).setDescripcion(linea[4]);
        habDoble.get(habDoble.size()-1).setOcupada(Integer.parseInt(linea[3]));


    }
    else if (linea[1].equals("3"))
    {
        habTriple.add(new HabitacionTriple());
        habTriple.get(habTriple.size()-1).setCodigo(linea[0]);
        habTriple.get(habTriple.size()-1).queCategoria(linea[2]);
        habTriple.get(habTriple.size()-1).setDescripcion(linea[4]);
        habTriple.get(habTriple.size()-1).setOcupada(Integer.parseInt(linea[3]));
    }
    else if (Integer.parseInt(linea[1]) > 3)
    {
        deptos.add(new Depto4Plus());
        deptos.get(deptos.size()-1).setCodigo(linea[0]);
        deptos.get(deptos.size()-1).queCategoria(linea[2]);
        deptos.get(deptos.size()-1).setDescripcion(linea[4]);
        deptos.get(deptos.size()-1).setOcupada(Integer.parseInt(linea[3]));

    }


}//end method
}//end class

The file I'm reading from has the following format:

0001;2;estandar;0;Habitación doble categoría Estandar
0002;3;estandar;0;Habitación triple categoría Estandar
0003;2;suite;0;Habitación doble categoría Suite
...
0010;3;estandar;0;Habitación triple categoría Estandar
0011;3;estandar;0;Habitación triple categoría Estandar
0012;3;estandar;0;Habitación triple categoría Estandar

And it goes on and on til code "0100" (hence it has 100 lines).

What I noticed is that I'm having an issue with "lines" array from line "0010" onwards. None of these lines from 0001 to 0010 present any trouble. And the other thing I noticed is that it only happens in positions [1], [2], [3], [4], but not in position [0] (for instance if I put "if (linea[0].equals("2"))" instead of [1] I would not have any issues).

So I'm kind of lost here, that's the main class only. It was working fine until I added 100 lines instead of just trying with 6 o 7 like I was doing a few mins ago.

Any help is appreciated, honestly I don't know what is causing it, although I suspect it has something to do with the way I'm reading the file.

Thanks in advance, Iván

UPDATE:

I just put a print before accessing to linea[1], it turns out that after 10 read lines, it stops reading or retrieving anything so array "linea" is empty. Why is that happening? I don't have a clue. Don't get the behavior at all!

(String[] linea, ArrayList<HabitacionDoble> habDoble, ArrayList<HabitacionTriple> habTriple,
                       ArrayList <Depto4Plus> deptos)
       {
               System.out.println ("line has a length of "+linea.length);
               if (linea[1].equals("2"))
               {
                       habDoble.add(new HabitacionDoble());
                       habDoble.get(habDoble.size()-1).setCodigo(linea[0]);
                       habDoble.get(habDoble.size()-1).queCategoria(linea[2]);
                       habDoble.get(habDoble.size()-1).setDescripcion(linea[4]);
                       habDoble.get(habDoble.size()-1).setOcupada(Integer.parseInt(linea[3]));


               }

The output once I run this:

    0001
line has 5 lenght
0002
line has 5 lenght
0003
line has 5 lenght
0004
line has 5 lenght
0005
line has 5 lenght
0006
line has 5 lenght
0007
line has 5 lenght
0008
line has 5 lenght
0009
line has 5 lenght
0010
line has 5 lenght

line has 1 lenght
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
       at guia3.Main.addHab(Main.java:71)
       at guia3.Main.main(Main.java:36)

EDIT WITH DEBUGGING:

I debugged (for the first time ever) a bit in Eclipse and this is what I found most strange during this stage (please follow the pic):

https://i.stack.imgur.com/DxkCV.png

As you may see, HeapCharBuffer just makes the line that follows "0010" completely blank, as well as breaking the format I established in .txt file for the following lines.

I don't even know if this is what is causing the issue but it certainly caught my attention (the screen is from the while loop, right after started reading the eleventh line).

UPDATE:

Well it was my fault apparently. If I paste the text from the .txt file here it also breaks the format as it looked when debugging. Why is this happening? It clearly is a file-related issue now.

0001;2;estandar;0;Habitación doble categoría Estandar
0002;3;estandar;0;Habitación triple categoría Estandar
0003;2;suite;0;Habitación doble categoría Suite
0004;4;superior;1;Departamento categoría Superior
0005;3;superior;1;Habitación triple categoría Estandar
0006;2;suite;0;Habitación doble categoría Suite
0007;3;suite;1;Habitación triple categoría Suite
0008;4;estandar;0;Departamento categoría estandar
0009;3;estandar;0;Habitación triple categoría Estandar
0010;3;estandar;0;Habitación triple categoría Estandar

0011;3;estandar;0;Habitación triple categoría Estandar
0012;
3;estandar;0;Habitación triple categoría Estandar
0013;
3;estandar;0;Habitación triple categoría Estandar

And this is how it looks in the txt (I thought it was ok but apparently something is wrong!):

https://i.stack.imgur.com/OJSuV.png

  • Can you post here the exact format of your 10th line (which causes the exception) plz? – Smajl Apr 26 '13 at 20:52
  • 1
    Step by step debugging should clear out the reason why you're getting the exception. Put a breakpoint on your `while` and see what happens at every iteration. – Voicu Apr 26 '13 at 20:52
  • 1
    If you have problems with line 11+ your should have poste line 11+ – Devolus Apr 26 '13 at 21:02
  • I just updated with line 11th and 12th, they have the exact same format though. I will try to debug but I'm no expert when it comes to debugging in Java. – user2163153 Apr 27 '13 at 01:41
  • Could you post the 10th line? For whatever reason it looks like there is something wrong with that line (an extra whitespace or something at the end of the line) and the scanner is reading an extra empty line after it. You could also build in a check and if the line read has a length of 1 skip it and move on to the next line. – DB5 Apr 27 '13 at 08:45
  • I just added line 10, unfortunately I already checked and it follows the exact same format as the following ones, so no problem should arise, yet it does. – user2163153 Apr 27 '13 at 15:19
  • I added the debugging screen I just took, please note that I'm no Java expert (you may have already noticed that haha) and I have never debugged in Java before. – user2163153 Apr 27 '13 at 15:32
  • Never too late to start learning it. You will need it later. If you're using Eclipse [this](http://www.vogella.com/articles/EclipseDebugging/article.html) page gives you the steps. – Voicu Apr 27 '13 at 17:10
  • Thanks for the link Voicu. It is indeed a very useful tool. – user2163153 Apr 27 '13 at 18:21
  • possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Raedwald Apr 01 '15 at 22:32

2 Answers2

1

Pointing to an error with "linea[1]" in the addHab method. Looks like the size of the array is less than 2.

Slihp
  • 763
  • 5
  • 12
  • This is indeed what is happening, but it happens for a reason I do not understand (I am familiar with the Out of Bounds concept). Check the update if you can please. – user2163153 Apr 27 '13 at 00:47
  • Interesting. It could be an encoding issue. The scanner my be reaching the end of the file prematurely because of it. I think notepad automatically saves with ANSI encoding so try saving it with UTF-8 encoding and setting the charset on your scanner to UTF-8 also. See if that solves the problem. – Slihp Apr 27 '13 at 03:28
  • Slihp I tried but unfortunately I did not work either. Thanks. – user2163153 Apr 27 '13 at 16:01
  • Could you post the complete first 12 lines of the file? – Slihp Apr 27 '13 at 16:54
  • Done! Please check the last update because something that I was unaware of is happening, it is a file related issue for sure. – user2163153 Apr 27 '13 at 18:24
0

while (x.hasNext()) should be while (x.hasNextLine()) since you are invoking x.nextLine() right after.

Suggestions:

Validate that linea.length > 2 to throw a more elegant Exception. Your input is a text file that could contain anything.

Open your Scanner inside a try and close it in a finally block so you don't have a resource leak:

Scanner scanner = null;
try {
    scanner = new Scanner(file);
    ...
} finally {
    if(scanner != null) {
        scanner.close();
    }
}
cahen
  • 15,807
  • 13
  • 47
  • 78
  • Hi Carlos, I just validated that linea is longer than 2, it happens to be that is not longer than 2 when it starts reading line eleventh from the file (I honestly can't understand why). The input is a text file indeed, but is formatted for every line in the same way, so it should (theoretically) behave the same way for everyline since they are all the same. Anyway I did what you suggested, I am still getting the error but at least the code is more elegant now. Thank you, any other tip/help is much welcome. – user2163153 Apr 27 '13 at 00:57