I am trying to loop asking coordinates and getting input from the scanner. I want to ask for input until the coordinates are valid. However I am really new with java and the loops confused me for this task. First I should print a console output asking the player to input a pair of board coordinates.
If the inputs are valid coordinates I will return the coordinates as a string array.
If the inputs are not valid coordinates I should print an error message and then ask again until I get valid coordinates.
public static String[] positionQuery(int dim, Scanner test_in) {
Scanner stdin = new Scanner(System.in);
System.out.println("Provide origin and destination coordinates.");
System.out.println("Enter two positions between A1-H8:");
String s1 = stdin.nextLine();
String[] coordinates = s1.split(" ");
String origin = coordinates[0];
String dest = coordinates[1];
while (!validCoordinate(origin, dim) && !validCoordinate(dest,dim)) {
System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
String s2 = stdin.nextLine();
String[] coordinates2 = s2.split(" ");
String origin2 = coordinates[0];
String dest2 = coordinates[1];
}
return new String[0];
}
I created a helper function validCoordinate(String, int)
that checks the validity.
How can I fix my code?