0

Class Lab9

        ScalesSolution s = new ScalesSolution("00100");
        s.println();
        s.SmallChange();
        s.println();

Method SmallChange in the ScalesSolution class

public void SmallChange() {

    int n = scasol.length();
    System.out.println("The length of scasol is "+ n);
    //CS2004 method generates a random integer number between 0 and n
    int p = CS2004.UI(0,n);

    StringBuilder sb = new StringBuilder(scasol);
    if (scasol.charAt(p) == '0') {
        sb.setCharAt(p, '1');
    } else {
        sb.setCharAt(p, '0');
    }
    scasol = sb.toString();
}

After running the code multiple times, I sometimes get the error

"String index out of range 5"

Even though this prints out

  The length of scasol is 5

every time it is run

Error: 00100 The length of scasol is 5 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5 at java.lang.String.charAt(String.java:658) at ScalesSolution.SmallChange(ScalesSolution.java:15) //point to if (scasol.charAt(p) == '0') at Lab9.main(Lab9.java:9)

I don't understand how sometimes it goes out of bounds. Any help please?

Adz
  • 2,809
  • 10
  • 43
  • 61

2 Answers2

5

Indexes' numbers start from 0, so if the code below generates the numbers between 0 and 5, it won't work for a string that has 5 characters (only indexes 0 to 4 will work).

//CS2004 method generates a random integer number between 0 and n
int p = CS2004.UI(0,n);

Change that to

int p = CS2004.UI(0,n-1);
Szymon
  • 42,577
  • 16
  • 96
  • 114
2

Strings start with array index 0. A string with length 5 has the indices 0, 1, 2, 3, 4. By reading from the 5th index with scasol.charAt(p) == '0', you are reading from a part of the string that is out of bounds.

To fix the issue, just make the index value 1 lower: scasol.charAt(p-1) == '0'

Blue Ice
  • 7,888
  • 6
  • 32
  • 52