Java Scanner Usage validateInt(Scanner keyboard, String message, String error)

Here you can find the source of validateInt(Scanner keyboard, String message, String error)

Description

validateInt - validates that a user has entered a correct value such as an integer.

License

Apache License

Parameter

Parameter Description
keyboard - the scanner class to recieve input from user

Return

- returns the integer value if valid

Declaration

public static int validateInt(Scanner keyboard, String message, String error) 

Method Source Code

//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;
    }
}

Related

  1. Tokenize(String s, String s2, String s3)
  2. toNumeric(String ip)
  3. toWords(String content)
  4. transformTXTandANNtoRQS(String TXT, String ANN)
  5. trim(String s)
  6. waitForEnter()
  7. waitForStopSignal()
  8. wrap(String msg, int wrapWidth, int wrapTolerance)