Skip to content

Instantly share code, notes, and snippets.

@Filmaluco
Created March 9, 2023 20:23
Show Gist options
  • Save Filmaluco/1c49d185214debdc30844686d141169c to your computer and use it in GitHub Desktop.
Save Filmaluco/1c49d185214debdc30844686d141169c to your computer and use it in GitHub Desktop.
input class
package pt.isec.pa.utils;
import java.util.Scanner;
public final class PAInput {
private PAInput() {}
private static Scanner sc;
static {
resetScanner();
}
public static void resetScanner() {
sc = new Scanner(System.in);
}
public static String readString(String title,boolean onlyOneWord) {
String value;
do {
if (title != null)
System.out.print(title);
else
System.out.print("> ");
value = sc.nextLine().trim();
} while (value.isBlank());
if (onlyOneWord) {
Scanner auxsc = new Scanner(value);
value = auxsc.next();
}
return value;
}
public static int readInt(String title) {
while (true) {
if (title != null)
System.out.print(title);
else
System.out.print("> ");
if (sc.hasNextInt()) {
int intValue = sc.nextInt();
sc.nextLine();
return intValue;
} else
sc.nextLine();
}
}
public static double readNumber(String title) {
while (true) {
if (title != null)
System.out.print(title);
else
System.out.print("> ");
if (sc.hasNextDouble()) {
double doubleValue = sc.nextDouble();
sc.nextLine();
return doubleValue;
} else
sc.nextLine();
}
}
public static int chooseOption(String title, String ... options) {
int option = -1;
do {
if (title != null)
System.out.println(System.lineSeparator()+title);
System.out.println();
for(int i = 0; i < options.length; i++) {
System.out.printf("%3d - %s\n",i+1,options[i]);
}
System.out.print("\nOption: ");
if (sc.hasNextInt())
option = sc.nextInt();
sc.nextLine();
} while (option < 1 || option > options.length);
return option;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment