Here you can find the source of validateInt(Scanner keyboard, String message, String error)
Parameter | Description |
---|---|
keyboard | - the scanner class to recieve input from user |
public static int validateInt(Scanner keyboard, String message, String error)
//package com.java2s; //License from project: Apache License import java.util.InputMismatchException; import java.util.Scanner; public class Main { /**//from w ww. j a va 2 s . co m * validateInt - validates that a user has entered a correct value such as * an integer. Re-ask user if invalid. * * @param keyboard - the scanner class to recieve input from user * @message - the message that will ask user for input * @error - the error to display if invalid * * @return - returns the integer value if valid **/ public static int validateInt(Scanner keyboard, String message, String error) { int returnValue = 0; boolean isError = true; do { try { System.out.println(message); returnValue = keyboard.nextInt(); keyboard.nextLine(); isError = false; } catch (InputMismatchException e) { System.out.println("\n" + error + "\n"); keyboard.nextLine(); } } while (isError); return returnValue; } }