Object-Oriented Programming with Java, part I – Exercise 69

This program uses the method palindrome to compare a string with its reverse and return true if it is a palindrome.

My Code

import java.util.Collections;
import java.util.Scanner;

public class Palindromi {

    public static boolean palindrome(String text) {
        // write code here
        int i = 0;
        String rev = new StringBuffer(text).reverse().toString();
        if ( rev.contentEquals(text)){
            return true;
        }

        return false;
    }

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        
        System.out.println("Type a text: ");
        String text = reader.nextLine();    
        if (palindrome(text)) {
            System.out.println("The text is a palindrome!");
        } else {
            System.out.println("The text is not a palindrome!");
        }
    }
}

Model Code

import java.util.Scanner;

 

public class Palindromi {

    public static String reverse(String text) {

        String reversed = "";

        int i = 0;

        while (i < text.length()) {

            char c = text.charAt(i);

            reversed = c + reversed;

            i++;

        }

        return reversed;

    }

 

    public static boolean palindrome(String text) {

        // write code here

        // text is a palindrome if it reads the same forward and backward

        boolean isPalindrome = text.equals(reverse(text));

        return isPalindrome;

    }

 

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

        

        System.out.println("Type a text: ");

        String text = reader.nextLine();    

        if (palindrome(text)) {

            System.out.println("The text is a palindrome!");

        } else {

            System.out.println("The text is not a palindrome!");

        }

    }

}

Comments

My code is better, but then that is a mix of me waking up, refusing to do the iteration because there must be an easier way and then spending half an hour on the Internet tracking down a nicer alternative. Time wise, I should have done it the model code way.

1 thought on “Object-Oriented Programming with Java, part I – Exercise 69”

Leave a comment