/* * This program shows two ways to validate input, specifically positive * integers. */ package validateintmethod; import java.util.Scanner; /** * * @author jcmtiernan */ public class ValidateIntMethod { /** * @param args the command line arguments */ public static void main(String[] args) { String intStrNum; Scanner in = new Scanner(System.in); int intStr; boolean valid = true; System.out.print("Please enter a positive integer. Your input will be validated: "); intStrNum = in.next(); in.nextLine(); intStr = validatePosInt(intStrNum); if (intStr != -1) { System.out.printf("You entered %d which is a positive integer. \n\n",intStr); } else { System.out.printf("You entered %s which is NOT a positive integer. \n\n",intStrNum); } System.out.print("Please enter a positive integer. Your will be required to enter valid data: "); intStrNum = in.next(); in.nextLine(); intStr = requirePosInt(intStrNum); System.out.printf("You entered %d which is a positive integer. \n\n",intStr); } /** validatePosInt * Checks a given input string to determine if it contains a positive integer. * If the input is positive, it is returned. If the input is negative, -1 is * returned. */ public static int validatePosInt(String intStrNum) { int intStr; boolean valid; valid = intStrNum.matches("\\d+"); //intStrNum = intStrNum+"Val"; if (valid) { // This turns the digits of string intStrNum into an int int length = intStrNum.length(); intStr = Integer.parseInt(intStrNum.substring(0,length)); //System.out.printf("You entered %s which is a positive integer. \n\n",intStrNum); return intStr; } else { //System.out.printf("You entered %s which is NOT a positive integer. \n\n",intStrNum); return -1; } } /** requirePosInt * Checks a given input string and returns the positive integer entered by the user. * If the input is not a positive integer, the user must enter a new value. The * user must enter values until a positive integer is given. */ public static int requirePosInt(String intStrNum) { int intStr = -1; boolean valid; Scanner in = new Scanner(System.in); do { valid = intStrNum.matches("\\d+"); if (valid) { // This turns the digits of string intStrNum into an int int length = intStrNum.length(); intStr = Integer.parseInt(intStrNum.substring(0,length)); //System.out.printf("You entered %d which is a positive integer. \n\n",intStr); } else { System.out.printf("You entered %s which is NOT a positive integer. \n\n",intStrNum); System.out.print("Please enter a positive integer: "); intStrNum = in.next(); in.nextLine(); valid = false; } } while(!valid); return intStr; } }