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

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.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!