Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Hugh Gordon - Palindrome Phone Number
- import java.util.*;
- import java.io.*;
- import java.text.NumberFormat;
- public class paliphone {
- public static void main(String[] args) throws IOException {
- String phoneNumber, justNumbers;
- StringTokenizer st;
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- // Prompt user for a phone number
- prompt("Enter a phone number (XXX) XXX-XXXX: "); phoneNumber = br.readLine();
- // Remove parantheses, hyphens, and spaces to get just the numbers
- justNumbers = toNumberString(phoneNumber);
- // Print whether the number is a palindrome
- print(isPalindrome(justNumbers)+"");
- // Print the number formatted with commas
- print(formatNumbers(justNumbers));
- }
- public static String toNumberString(String str) {
- // Break the string into tokens (Removes " " "(" ")" and "-" characters)
- StringTokenizer st = new StringTokenizer(str, " ()-");
- StringBuffer returnStr = new StringBuffer("");
- // Put the tokens back together without the delimiters
- while (st.hasMoreTokens()) {
- returnStr.append(st.nextToken());
- }
- return returnStr.toString();
- }
- public static boolean isPalindrome(String str) {
- int i;
- char[] chars = str.toCharArray();
- StringBuffer buf = new StringBuffer(str);
- // check if the string is the same as it is in reverse
- boolean isPalindrome = buf.toString().equalsIgnoreCase(buf.reverse().toString());
- return isPalindrome;
- }
- public static String formatNumbers(String numbers) {
- // Convert the string into a long number
- long num = Long.parseLong(numbers);
- // Declare an instance of NumberFormat
- NumberFormat nf = NumberFormat.getInstance();
- // Format the string with NumberFormat
- String formatted = nf.format(num);
- return formatted;
- }
- // Shortcuts for System.out.print and System.out.println respectively
- public static void prompt(String out) { System.out.print(out); }
- public static void print(String out) { System.out.println(out); }
- }
Advertisement
Add Comment
Please, Sign In to add comment