简体   繁体   中英

Java- Having trouble figuring out why there's an arrayOutOfBoundsException going on in my cache simulation

This method is supposed to:

  1. Poke through a text file filled with 32 rows of 10 hex strings.

  2. Break them apart using a whitespace in between each as delimiter.

  3. Store the hex strings in an array with 10 indices.

  4. Since I'm simulating memory I then load the array into a simulated Register class.

I've gotten it to this step, but I'm having trouble seeing why this arrayOutOfBounds exception is occurring for the arrayString[] array.

public void setRegister(Register[] r) throws FileNotFoundException{ //pokes through the 
                                                                    //file and extracts hexes

    Scanner s = new Scanner("/Users/adpitt/Documents/document.txt"); //macOS path
    Register reggie = new Register(); //holding reg

    while (s.hasNextLine()) {
    String str = s.nextLine(); //slam a line into the string

         for(int i = 0; i <= mainMemSize-1; i++){ //iterate through array of registers

             for(int j = 0; j <= this.length-1; j++){

                 String arrayString[] = str.split("\\s+");//smash them to     
                                                          //pieces, space = delimiter

                 reggie.reg[j] = arrayString[j];//THIS IS WHERE THE EXCEPTION OCCURS. 
                                                //I believe it's in arrayString[j], 
                                                //not sure why.

              }//complete reggie!
             r[i] = reggie;//load reggie into the register array to complete mm
          }
     }
    s.close();

}

Why are you splitting the str in the inner loop? The str value is not changing anywhere inside those for loops. Can you try moving it out of the for loops, and just after String str=s.nextLine();

Also what is this.length ? what if this.length-1 is greater than 10 (assuming str.split returns 10 hex strings, as per your initial description)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM