Comment the input class

This commit is contained in:
andrew
2022-01-10 20:26:50 +00:00
parent 0614831f46
commit ea5c2cf72d

View File

@@ -3,12 +3,15 @@ import java.io.InputStreamReader;
import java.io.IOException; import java.io.IOException;
import java.text.NumberFormat; import java.text.NumberFormat;
// This class handles reading input from the player
// Each input is an x and y coordinate
// e.g. 5,3
public class Input { public class Input {
private BufferedReader reader; private BufferedReader reader;
private NumberFormat parser; private NumberFormat parser;
private int scale; private int scale; // size of the sea, needed to validate input
private boolean isQuit; private boolean isQuit; // whether the input has ended
private int[] coords; private int[] coords; // the last coordinates read
public Input(int seaSize) { public Input(int seaSize) {
scale = seaSize; scale = seaSize;
@@ -18,22 +21,27 @@ public class Input {
public boolean readCoordinates() throws IOException { public boolean readCoordinates() throws IOException {
while (true) { while (true) {
// Write a prompt
System.out.print("\nTarget x,y\n> "); System.out.print("\nTarget x,y\n> ");
String inputLine = reader.readLine(); String inputLine = reader.readLine();
if (inputLine == null) { if (inputLine == null) {
System.out.println("Game quit\n"); // If the input stream is ended, there is no way to continue the game
System.out.println("\nGame quit\n");
isQuit = true; isQuit = true;
return false; return false;
} }
// split the input into two fields
String[] fields = inputLine.split(","); String[] fields = inputLine.split(",");
if (fields.length != 2) { if (fields.length != 2) {
// has to be exactly two
System.out.println("Need two coordinates separated by ','"); System.out.println("Need two coordinates separated by ','");
continue; continue;
} }
coords = new int[2]; coords = new int[2];
boolean error = false; boolean error = false;
// each field should contain an integer from 1 to the size of the sea
try { try {
for (int c = 0 ; c < 2; ++c ) { for (int c = 0 ; c < 2; ++c ) {
int val = Integer.parseInt(fields[c].strip()); int val = Integer.parseInt(fields[c].strip());
@@ -46,6 +54,7 @@ public class Input {
} }
} }
catch (NumberFormatException ne) { catch (NumberFormatException ne) {
// this happens if the field is not a valid number
System.out.println("Coordinates must be numbers"); System.out.println("Coordinates must be numbers");
error = true; error = true;
} }