import java.util.Scanner; /** * Reads in a social security number (SSN), formatted as XXX-XX-XXXX, where the X's * represent digits. Adds 1 to that number and prints the result in the same * format. * * @author pollen */ public class NextSsn { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a social security number " + "in the format XXX-XX-XXXX: "); String ssnText = in.next(); // Parse out the digit blocks from the SSN. String firstBlock = ssnText.substring(0, 3); String secondBlock = ssnText.substring(4, 6); String thirdBlock = ssnText.substring(7); // Parse and combine the blocks into a single integer. We could do this by // concatenating them as strings and then parsing, or we could parse each // one individually and then combine them, using powers of 10 to shift the // digits as necessary. We choose the former approach here. int ssn = Integer.parseInt(firstBlock + secondBlock + thirdBlock); // Increment the SSN. ssn++; // Convert the new SSN into text. Use String.format to make sure the number is // zero-padded to 9 digits. We will cover this in briefly in Friday's lecture. ssnText = String.format("%09d", ssn); // Break out the digit blocks from the new SSN. firstBlock = ssnText.substring(0, 3); secondBlock = ssnText.substring(3, 5); thirdBlock = ssnText.substring(5); // Print the result, inserting hyphens. System.out.println(firstBlock + "-" + secondBlock + "-" + thirdBlock); } }