Refactor input handling in NetBuilderInteractive to improve error management and streamline user prompts

This commit is contained in:
2025-02-19 12:14:53 +01:00
parent 744df75d41
commit 76adc91a43

View File

@@ -166,13 +166,12 @@ public class NetBuilderInteractive {
* @return the answer * @return the answer
*/ */
private <T> T ask(String ask, Function<String, T> parser) { private <T> T ask(String ask, Function<String, T> parser) {
var totalRows = ask.chars().filter(ch -> ch == '\n').count() + 1; var totalRows = ask.chars().filter(ch -> ch == '\n').count();
var startLine = "\033[" + totalRows + "A"; var ask2 = "\033[" + totalRows + "A" + ask;
var clearLine = "\033[K";
var ask2 = startLine + clearLine + ask;
var first = true; var first = true;
try {
while (true) { while (true) {
this.out.print(first ? ask : ask2); this.out.print(first ? ask : ask2);
var line = this.scanner.nextLine(); var line = this.scanner.nextLine();
@@ -182,8 +181,12 @@ public class NetBuilderInteractive {
var value = parser.apply(line); var value = parser.apply(line);
return value; return value;
} catch (Exception e) { } catch (Exception e) {
this.out.print("\033[A\033[K"); // clear the line
} }
} }
} catch (Exception e) {
return null; // normally when the scanner is closed
}
} }
/** /**
@@ -203,8 +206,12 @@ public class NetBuilderInteractive {
var string = builder.toString(); var string = builder.toString();
var choice = 0; var choice = 0;
while (choice < 1 || choice > options.length) choice = ask(string, val -> {
choice = ask(string, Integer::parseInt); var x = Integer.parseInt(val);
if (x < 1 || x > options.length)
throw new NumberFormatException(); // retry the question
return x;
});
return choice; return choice;
} }