KHD

final paliphone

KHD
Sep 11th, 2013
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Hugh Gordon - Palindrome Phone Number
  2. import java.util.*;
  3. import java.io.*;
  4. import java.text.NumberFormat;
  5.  
  6. public class paliphone {
  7.   public static void main(String[] args) throws IOException {
  8.     String phoneNumber, justNumbers;
  9.     StringTokenizer st;
  10.     BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  11.     // Prompt user for a phone number
  12.     prompt("Enter a phone number (XXX) XXX-XXXX: "); phoneNumber = br.readLine();
  13.     // Remove parantheses, hyphens, and spaces to get just the numbers
  14.     justNumbers = toNumberString(phoneNumber);
  15.     // Print whether the number is a palindrome
  16.     print(isPalindrome(justNumbers)+"");
  17.     // Print the number formatted with commas
  18.     print(formatNumbers(justNumbers));
  19.   }
  20.   public static String toNumberString(String str) {
  21.     // Break the string into tokens (Removes " " "(" ")" and "-" characters)
  22.     StringTokenizer st = new StringTokenizer(str, " ()-");
  23.     StringBuffer returnStr = new StringBuffer("");
  24.     // Put the tokens back together without the delimiters
  25.     while (st.hasMoreTokens()) {
  26.       returnStr.append(st.nextToken());
  27.     }
  28.     return returnStr.toString();
  29.   }
  30.   public static boolean isPalindrome(String str) {
  31.     int i;
  32.     char[] chars = str.toCharArray();
  33.     StringBuffer buf = new StringBuffer(str);
  34.     // check if the string is the same as it is in reverse
  35.     boolean isPalindrome = buf.toString().equalsIgnoreCase(buf.reverse().toString());
  36.     return isPalindrome;
  37.   }
  38.   public static String formatNumbers(String numbers) {
  39.     // Convert the string into a long number
  40.     long num = Long.parseLong(numbers);
  41.     // Declare an instance of NumberFormat
  42.     NumberFormat nf = NumberFormat.getInstance();
  43.     // Format the string with NumberFormat
  44.     String formatted = nf.format(num);
  45.     return formatted;
  46.   }
  47.   // Shortcuts for System.out.print and System.out.println respectively
  48.   public static void prompt(String out) { System.out.print(out); }
  49.   public static void print(String out) { System.out.println(out); }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment