Polishing invalid input handling

This commit is contained in:
Imbus 2023-12-11 14:25:04 +01:00
parent 7e5253fb4b
commit d056732add

View file

@ -94,24 +94,31 @@ public class SudokuController {
int row = view.getSelectedRow();
int col = view.getSelectedColumn();
// The value to be inserted into the cell
// Zero inicates an empty cell
// Negative values are invalid
int value = 0;
String cellValue = view.getCellValue(row, col);
// We need to check for null and empty string
if (cellValue == null || cellValue.equals("")) {
value = 0;
} else {
try {
value = Integer.parseInt(cellValue);
} catch (NumberFormatException ex) {
value = 0;
value = -1;
}
}
// If the input is invalid
if (!model.isLegal(row, col, value)) {
// If the input is invalid, value < 0 indicates parse error
if (!model.isLegal(row, col, value) || value < 0) {
value = 0;
view.showErrorMessage("Invalid input. Try again.");
}
// Update the model and view
model.set(row, col, value);
view.updateView(model.getBoard());
}