My code prints out an array which is already declared then asks for user input. User is supposed to enter a number in the format xy or type quit to stop using the program. After getting user input it prints out the element of the array using x as row and y as column number which is followed by setting that index to 0 and printing the new array. I have so far achieved most of it apart from accepting only integers or "quit" from the user. If user enters another string apart from "quit" the program crashes. This is my code. import java.util.Scanner;
public class Exercise23 {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int [][] array = {
{0, 1, 4, 5},
{3, 7, 9, 7},
{1, 8, 2, 1}
};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
boolean exitCon = false;
do {
System.out.println("Please enter a number in the format 'xy' with no spaces in between or enter 'quit' to stop");
String xy = read.nextLine();
if (!"quit".equals(xy)) {
String x = xy.substring(0, 1);
String y = xy.substring(1);
int row = Integer.parseInt(x);
int column = Integer.parseInt(y);
if (0 <= row && 0 <= column && row <= 2 && column <=) {
System.out.println();
System.out.println(array[row][column]);
array[row][column] = 0;
System.out.println();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
System.out.println();
} else { System.out.println("The number has to be in range 00-23 inclusive considering the format 'xy'.");
}
} else if (xy.equals("")) {
System.out.println("You can only enter integers or 'quit'.");
} else {
exitCon= true;
}
} while (!exitCon);
}
}
The problem is in this bit
String xy = read.nextLine();
if (!"quit".equals(xy)) {
String x = xy.substring(0, 1);
String y = xy.substring(1);
int row = Integer.parseInt(x);
int column = Integer.parseInt(y);
if (0 <= row && 0 <= column && row <= 2 && column <= 3) {
System.out.println();
System.out.println(array[row][column]);
array[row][column] = 0;
System.out.println();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
System.out.println();
} else { System.out.println("The number has to be in range 00-23 inclusive considering the format 'xy'.");
}
} else if (xy.equals("")) {
System.out.println("You can only enter integers or 'quit'.");
} else {
exitCon= true;
I get this error "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1 at java.lang.String.substring(String.java:1963) at Exercise23.main(Exercise23.java:26) "