/* * This program accepts an input that should be a positive integer * and this program validates the input to verify that it is a * positive integer. */ package validateintegerstrings; import java.util.Scanner; /** * @author jcmtiernan */ public class ValidateIntegerStrings { /** * @param args the command line arguments */ public static void main(String[] args) { String intStrNum; int intStr; boolean valid = true; Scanner in = new Scanner(System.in); boolean contCheck = true; // Does the user want to continue? do { System.out.print("Please enter a positive integer. To quit, type capital Q: "); intStrNum = in.next(); in.nextLine(); // "Q" will indicate that the user wants to stop running the program if (intStrNum.equals("Q")) { contCheck = false; } else { /* The ".matches" method compares the values in the string against \\d+ . * \\d+ is a regular expression that tests to see if all characters in the * string are digits (\\d) and there can be 1 or more digits (+) */ 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); } } } while(contCheck); } }