0

I'm trying to read a file with this method:

    public static char [] llegir() {
    Palabra nova = new Palabra();
    botarBlancs();
    while ((lletra != fiSequencia) && // No ha acabat la seqüència
            (lletra != blanc)) { // Hi ha prou espai
        nova.lletres[nova.llargaria++] = lletra;
        lletra = leerCarTeclado();
    }
    //System.out.println(nova.girar());
    return nova.lletres;
}

(botarBlancs() simply jumps blank spaces to distinguish one word from another)

Here's the code I'm using:

    public static void generador_de_cartas() throws Exception{
    Palabra pl = new Palabra();

    FileReader fr = new FileReader("datos_clientes.txt");
    BufferedReader br = new BufferedReader(fr);
    String line = br.readLine();
    char [] linea;

    while (line != null) {
        linea=line.toCharArray();
        linea=Palabra.llegir();
        System.out.println(linea);
        line=br.readLine();

    }

    br.close();
    fr.close();
}

And it gives me a Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20 at method llegir() where it says: nova.lletres[nova.llargaria++] = lletra;

How can I solve this??

Any ideas on how to read a line of the file using that method??

thank you in advance

***********************EDIT***********************

Here's what I've tried:

    public static void generador_de_cartas() throws Exception {
    Palabra pl = new Palabra();
    char[] tipo1 = {'t', '1'}, tipo2 = {'t', '2'}, tipo3 = {'t', '3'}, nRef = {'#', 'n'}, dRef = {'#', 'd'};
    FileReader fr = new FileReader("datos_clientes.txt");
    BufferedReader br = new BufferedReader(fr);
    String line = br.readLine();
    char[] linea;

    while (line != null) {
        linea = line.toCharArray();
        Palabra.llegir(); //reads line 
        if (Palabra.llegir() == tipo1) {
            //code that creates a new file following the pattern of tipo 1 files
        } else {
            if (Palabra.llegir() == tipo2) {
                //code that creates a new file following the pattern of tipo 2 files
            } else {
                if (Palabra.llegir() == tipo2) {
                    //code that creates a new file following the pattern of tipo 3 files
                }
            }
            line = br.readLine();

        }
        line = br.readLine(); //reads following line
    }

    br.close();
    fr.close();
}

But it keeps reporting the same exception.

The main idea of the program consists in creating a text file for each person represented in the differents line of the main file (datos_clientes.txt), the files have a different text or pattern depending on the person.

One line of the main file looks like this:

t1 #n name #d address (t1 is the pattern of the file that will be created)

After that I have to read the name of the person, save it, read the address, save it and writing it in the file that was created for them.

This is what I've done so far, just the method that creates the different files.

Hope you can help me

Thanks!!

This is the class Palabra:

public class Palabra {

public static final char blank = ' ';
public static final char endSequence = '\n';
// Constants privades
// Llargària màxima d'una paraula
private static final int MAXIM = 20;
// ATRIBUTS
private char[] letters;
private int length;
// atribut de classe, per simplificar les operacions de lectura
private static char letter = ' ';
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++EXTRA
private static char[] frase = null;
private static int indice;

// INTERFICIE
// Constructor
public Palabra() {
    letters = new char[MAXIM];
    length = 0;
}

public static char[] llegir() {
    Palabra nova = new Palabra();
    botarBlancs();
    while ((letter != endSequence) && // No ha acabat la seqüència
            (letter != blank)) { // Hi ha prou espai
        if (nova.length < nova.letters.length) {
            nova.letters[nova.length++] = letter;
            letter = leerCarTeclado();

        }
    }

    return nova.letters;
}

public boolean esIgualA(Palabra b) {
    boolean iguals = length == b.length;
    for (int idx = 0; (idx < length) && iguals; idx++) {
        iguals = letters[idx] == b.letters[idx];
    }
    return iguals;
}

public static boolean iguals(Palabra a, Palabra b) {
// using previous esIgualA
    return a.esIgualA(b);
}

public static void botarBlancs() {
    while (letter == blank) {
        letter = leerCarTeclado();
    }
}

static public char leerCarTeclado() {
    char res = '.';
    if (frase != null) {
        res = frase[indice++];
    }
    return res;
}

}

I changed some to non-static and at least I can run it, now I'm trying to know if I'm reading the line properly. If I'm not wrong with method llegir() I can read one word and save it, right? Correct me if I'm wrong. I'm trying to read the first "word" in the line, that is "t1" for example, then I compare it to another char array and I tried to print to check if the code works, but it doesn't. What am I doing wrong??

        while (line != null) {
        linea = line.toCharArray();
        char [] tipo=Palabra.llegir(); //reads first word 

        if (tipo == tipo1) {
           System.out.print("tipo1") ;//code that creates a new file following the pattern of tipo 1 files
        } else {
            if (tipo == tipo2) {
                System.out.print("tipo2") ;//code that creates a new file following the pattern of tipo 2 files
            } else {
                if (tipo == tipo2) {
                   System.out.print("tipo3") ; //code that creates a new file following the pattern of tipo 3 files
                }
            }


        }
        line = br.readLine(); //reads following line
    }
Johnny
  • 41
  • 1
  • 10

2 Answers2

2

You should start at the start of the array each time the method is called i.e. 0 and you should make sure you are not attempting to access an index which doesn't exist i.e. This must be true nova.llargaria < nova.lletres.length

Note: you are reading a line but you appear to be ignoring it. Is this intended?

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • I'm kind of lost if I'm honest. I want to read each line of the file, save it into a char array and read it with that method, because the lines of the file have this structure: t1 #n whatever #d whatever... and I want to read until the first #n and save that into an array, then until #d and the same, how can I do that using that method llegir()?? Thanks @Peter Lawrey – Johnny Jan 26 '16 at 19:38
  • @Maria I suggest you write code which does exactly what you suggest, with a comment with the lines of code to say what they should be doing. You have code which doesn't appear to be related to what you are trying to do. – Peter Lawrey Jan 26 '16 at 19:48
  • okay, I will try to do that, but I must use that method and I think it's the method what is giving me problems. Could you explain me where I'm not writing a code related to what I'm trying to do? Thanks again @Peter Lawrey – Johnny Jan 26 '16 at 20:00
  • @Maria It's not clear from you code why you set `linea=line.toCharArray();` as you don't appear to use it anywhere else. I suggest you make it a local variable and pass it to methods which use it. Your static method `llegir() ` creates a `new Palabra()` thou it is not clear why it does this as only one field is used so you could have just created the variable you really needed instead. – Peter Lawrey Jan 27 '16 at 09:32
  • I think I got it, but how can I solve the problem of the exception in method llegir()? I tried : if (nova.llargaria < nova.lletres.length) then nova.lletres[nova.llargaria++] = lletra ... but when I run it it just keeps loading and doesn't do anything. @Peter Lawrey – Johnny Jan 27 '16 at 09:56
  • @Maria In this case, you have a bug in the rest of your code. It's not easy for me to read as it's not in ENglish but the structure isn't clear either because I cannot see from the code how anything hangs together. i.e. you set variable sin one place and use other in another place but I can see if these are related in any way. – Peter Lawrey Jan 27 '16 at 09:59
  • Just added the class, with the variables in english so you can try to understand it better. Thanks @Peter Lawrey – Johnny Jan 27 '16 at 10:13
  • I highly recommend you try writing it without any mutable `static` fields. See how many fields can be made local variables, and the rest you can make non-static fields. – Peter Lawrey Jan 27 '16 at 10:27
  • i changed static to non static and I can run it, now i'm not sure if what I'm doing is right. I edited the question above @Peter Lawrey – Johnny Jan 27 '16 at 10:52
  • @Maria you set `linea` but it's not clear how this is used. – Peter Lawrey Jan 27 '16 at 12:07
  • I use it as the text llegir() has to read from. @Peter Lawrey – Johnny Jan 27 '16 at 12:21
  • @Maria parsing a `char[]` is pretty low level. Are you sure you shouldn't be working with a `String`? – Peter Lawrey Jan 27 '16 at 12:26
  • But can I use llegir() to read from a String?? @Peter Lawrey – Johnny Jan 27 '16 at 12:39
  • @Maria The `line` is a `String` and extracting a String from it is pretty simple. Also when you try to compare Strings there is an `.equals()` method so it is easier to work with than `char[]` – Peter Lawrey Jan 27 '16 at 13:14
  • So you suggest that I don't use method llegir()? @Peter – Johnny Jan 27 '16 at 13:27
  • @Maria I can't see what the method does, so it is hard to say. – Peter Lawrey Jan 27 '16 at 14:53
  • It's supposed to read from a sequence of characters @Peter – Johnny Jan 27 '16 at 15:25
  • @Maria Manipulating `char[]` directly is not something most Java programmers do, ever. I suggest you get it working with a String first and when this compiles and works, change the code to use a `char[]` instead as it is much harder to work with a debug. – Peter Lawrey Jan 27 '16 at 15:29
  • Thanks and thanks for the other answer too!! @Peter – Johnny Jan 27 '16 at 15:40
0

You're not giving us much enough information... but:

Open this in a debugger (Intellij IDEA has a great one for example). If you create a breakpoint by clicking in the left margin and right-click on it, you can tell it the conditions under which to stop at the breakpoint.

Tell it to stop at the breakpoint when nova.llargaria is >= nova.lletres.length. This will let you see what is going on right before it crashes.

Also, you can just check if nova.llargaria is >= nova.lletres.length in the code and continue; to skip past it so it doesn't crash in that case.

John Humphreys
  • 37,047
  • 37
  • 155
  • 255