Skip to content

Instantly share code, notes, and snippets.

@OlabodeAbesin
Last active May 5, 2020 17:42
Show Gist options
  • Save OlabodeAbesin/e032c142c6eaf36f8025a6a1dc415db3 to your computer and use it in GitHub Desktop.
Save OlabodeAbesin/e032c142c6eaf36f8025a6a1dc415db3 to your computer and use it in GitHub Desktop.
Recursively take input until validation is right
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void validateMenu(Scanner sc) {
System.out.print("Please enter a valid input, between 1 and 6: ");
int menuChoice = sc.nextInt();
try {
if (menuChoice < 1 || menuChoice > 6 || menuChoice != (int)menuChoice) {
validateMenu(sc);
}
} catch(Exception e) {
validateMenu(sc);
}
}
public static void validateTransactionType(Scanner sc) {
System.out.print("Please enter transaction type [1 -- Cash 2 -- Card]: ");
int transChoice = sc.nextInt();
try{
if (transChoice < 1 || transChoice > 2 || transChoice != (int)transChoice) {
validateTransactionType(sc);
}
}
catch(Exception e){
validateTransactionType(sc);
}
}
public static void main(String[] args) {
// Menu menu = new Menu(inventoryFilePath);
// System.out.println("\tMENU\n********************");
// int i = 1;
// for (MenuItem item : menu.getMenu()) {
// System.out.println(i + ". " + item.getItemName() + "\t\t" + item.getItemPrice() + "0");
// i++;
// }
// System.out.println(i + ". " + "Exit");
Scanner sc = new Scanner(System.in);
validateMenu(sc);
System.out.println("Your menu input is valid");
validateTransactionType(sc);
System.out.println("Your Transaction Type input is valid");
sc.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment