Advertisement
HasteBin0

Java Palindrome Exercise

Jun 25th, 2017
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.36 KB | None | 0 0
  1. package palindromes;
  2.  
  3. import java.util.Scanner;
  4.  
  5. /**
  6.  *
  7.  * @author Aidan
  8.  */
  9. public class Palindromes {
  10.  
  11.     static {
  12.         renew();
  13.     }
  14.  
  15.     private static void renew() {
  16.         input = new Scanner(System.in);
  17.     }
  18.  
  19.     private static Scanner input;
  20.  
  21.     public static void main(String[] args) {
  22.         Integer in_value;
  23.  
  24.         do {
  25.             System.out.print("Enter the number to flip: ");
  26.             try {
  27.                 in_value = input.nextInt();
  28.             } catch (Exception e) {
  29.                 in_value = 0;
  30.             }
  31.             renew();
  32.         } while (in_value <= 0);
  33.  
  34.         System.out.println("Flipped, " + in_value + " resolves to " + flip(in_value) + '.');
  35.         System.out.println(check(in_value) ? "Yes, " + in_value + " is a Palindrome." : "No, " + in_value + " isn't a Palindrome.");
  36.         System.out.flush();
  37.  
  38.     }
  39.  
  40.     // Flip an Integer in base 10.
  41.     private static Integer flip(final Integer x) {
  42.         Integer tmp_out = 0, tmp_in = x, tens = (int) Math.log10(x);
  43.         do {
  44.             tmp_out += ((int) Math.pow(10.0, (double) tens--)) * (tmp_in % 10);
  45.             tmp_in /= 10;
  46.         } while (tmp_in != 0);
  47.         return tmp_out;
  48.     }
  49.  
  50.     // Check if an Integer is a Palindrome.
  51.     private static Boolean check(final Integer x) {
  52.         return x.equals(flip(x));
  53.     }
  54.  
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement