Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Javascript error, string index out of bounds? static void readData(Scanner input

ID: 3606906 • Letter: J

Question

Javascript error, string index out of bounds?  

static void readData(Scanner input) {
int TargetRect_w = input.nextInt();
int TargetRect_h = input.nextInt();
int NumBlocks = input.nextInt();
while (input.hasNext()) {
String Rectangle_line = input.nextLine();
Rectangle_line = Rectangle_line.replace("\s/g","");
int width = 2;
int height = (NumBlocks*2);

char rect[][] = new char[height][width];

int charCount = 0;
for (int c = 0; c < width; c++) {
for (int r = 0; r < height; r++) {
rect[r][c] = Rectangle_line.charAt(charCount);
charCount += 1;
}
}
System.out.println( rect );
}
}

I'm getting this exception thrown and I'm confused as to why?

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1

   at java.lang.String.charAt(String.java:658)

   at Block_V21.readData(Block_V21.java:66)

   at Block_V21.main(Block_V21.java:17)

As I understand it, this error is popping up because I'm searching for a position in an array that is empty or null, but when I introduce the char rect as an array dependent on height and width (the former of which is set by scanner input information), isn't that array position being filled/ why would such an exception be thrown? Thank you.

Explanation / Answer

You didn't mentioned what input source you are creating a scanner object.

"String Rectangle_line = input.nextLine();" // In this line input.nextLine() is returning a empty string. And when u try to execute "Rectangle_line.charAt(charCount);", Rectangle_line variable contains empty string hence its giving java.lang.StringIndexOutOfBounds Exception. Make sure you have a line in the input source you provided or else check the condition whether Rectangle_line variable is empty or not before executing for loops.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote