13 Replies - 6341 Views - Last Post: 16 October 2010 - 08:00 PM Rate Topic: -----

#1 cyberbemon  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 14-October 10

Palindrome JAVA

Posted 14 October 2010 - 08:53 AM

Hello guys i'm writing a program that checks whether the entered string is a palindrome or not and prints the reverse of the suffix of the enteres string.The problem is when i enter a string ROADR it says its a palindrome which is not right.How do i fix this? i have posted my code below thank you :)

import javax.swing.JOptionPane;



public class Palindrome{
    public static void main(String[]args){
        String input = JOptionPane.showInputDialog("enter the string");//string input
        String input1 = input.toUpperCase();//converts the entered string to upper case
        char input3 [] = input1.toCharArray();//put it in to an array
        char input4[] = new char[99999999];//used for suffix
        input4= input3;
        int first=0;//first letter of the string
        int last= input1.length()-1;//last letter
        
        if(last<=0)//if the string is empty
        {
            JOptionPane.showMessageDialog(null, "Try again and  enter a valid string");
            return;
        }
        while (first<last)//goes to the middle letter
        {
            if(input1.charAt(first)!= input1.charAt(last))//if its not equal
            {
                System.out.println("The string is not a palindrome");
                System.out.print("suffix: "+input4[0]);
                
                for(int x=last;x>=1;x--)
                {
                    System.out.print(input4[x]);
                }
                System.out.println();
                System.out.print("backwards is: ");
                for(int i =last;i>=0;i--)
                {
                        System.out.print(input3[i]);
                        
                            
                }
                
                return;
                
                
            }
            else
            {
                System.out.println("The string is  a palindrome");
                System.out.print("suffix: "+input4[0]);
                for(int x=last;x>=1;x--)
                {
                    System.out.print(input4[x]);
                }
                System.out.println();
                System.out.print("backwards is: ");
                for(int i =last;i>=0;i--)
                {
                        System.out.print(input3[i]);
                            
                }
                    
                
            }
        }
    }
        
        
        
        
    }
    


Is This A Good Question/Topic? 0
  • +

Replies To: Palindrome JAVA

#2 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10364
  • View blog
  • Posts: 38,392
  • Joined: 27-December 08

Re: Palindrome JAVA

Posted 14 October 2010 - 09:23 AM

You're doing a little too much work here. No need to convert the String to a char[]. Just use a for loop to go from 0 through length()/2, comparing the charAt(i) to the charAt(length()-1-i).
for(int i = 0; i < myStr.length()/2; i++){
    //if the charAt(i) != the charAt(myStr.length()-1-i)
    //then you can terminate the loop, as you do not have a palindrome
}

//if you get through the loop without terminating
//then myStr is a palindrome


Was This Post Helpful? 1
  • +
  • -

#3 mostyfriedman  Icon User is offline

  • The Algorithmi
  • member icon

Reputation: 727
  • View blog
  • Posts: 4,473
  • Joined: 24-October 08

Re: Palindrome JAVA

Posted 14 October 2010 - 09:24 AM

there are a few problems i can spot here. The first one is once a character from the beginning is equal to the character in the end, it will print out "this is a palindrome" which is incorrect, you cannot confirm that a string is a palindrome unless you go through the whole string. The other thing is, i think this code would put you in an infinite loop, I dont seem to see you updating first and last.
Was This Post Helpful? 0
  • +
  • -

#4 Luckless  Icon User is offline

  • </luck>
  • member icon

Reputation: 292
  • View blog
  • Posts: 1,146
  • Joined: 31-August 09

Re: Palindrome JAVA

Posted 14 October 2010 - 09:28 AM

how about:

String string = someInput;
//we begin by assuming it is
boolean isPal = true;

//while true and not in the middle
while(isPal && (first < last)){
     if(string.charAt(first) == string.chatAt(last)){
         //will check the next two chars next time around
         first++;
         last--;
         //still true
         isPal = true;
     }
     //otherwise, we break the loop
     else{
          isPal = false;
}

System.out.println( "Is it a palindrome?: " + isPal);



this is the basic structure and you can spiffy it up with your error checking statements yourself.

to print it backwards, you just have to run a for loop in reverse order, printing .charAt(length - 1) to .charAt(0). A little more concise, eh? You have the right train of thought though--I just don't like using unnecessary char arrays :bigsmile:
Was This Post Helpful? 1
  • +
  • -

#5 cyberbemon  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 14-October 10

Re: Palindrome JAVA

Posted 14 October 2010 - 03:13 PM

thank you guys for your reply :)..so i edited my code and this is wat it looks like now..how ever i'm still a bit confused about the revers string.(keeping the first letter and reversing th e rest for eg.tom -> tmo.).how do i do it without an array?.@Luckless i tried to use your reverse method but i cudn;t get it to work.. :(
public class palindrome1 {
    public static void main(String[] args) 
    {
        String input = JOptionPane.showInputDialog("enter the string");//string input
        String input1 = input.toUpperCase();//converts the entered string to upper case
        for(int i = 0; i < input1.length()/2; i++){
            if (input1.charAt(i) != input1.charAt(input1.length()-1-i))
                    {
                        System.out.println("the entered string is not a palindrome");
                        break;
                    }
            else 
            {
                System.out.print("the entered string is a palindrome");
                break;
                
            }
        }
    }

}

This post has been edited by cyberbemon: 14 October 2010 - 03:14 PM

Was This Post Helpful? 0
  • +
  • -

#6 jimdandy75  Icon User is offline

  • D.I.C Regular

Reputation: 37
  • View blog
  • Posts: 311
  • Joined: 30-June 08

Re: Palindrome JAVA

Posted 14 October 2010 - 05:03 PM

You could try flipping the original string, then comparing the 2 strings. Then from there you already have a flipped string to print out what you need.
import javax.swing.JOptionPane;

public class Pali{

	public static void main (String[] args) {
		String orig = JOptionPane.showInputDialog("enter the string");//string input
		String flipped = reversed(orig);

		if(orig.equals(flipped))
		System.out.println("This IS a palindrome.");
		else
		System.out.println("This IS NOT palindrome.");
		
		System.out.print(orig.charAt(0));
		System.out.print(flipped.substring(0, flipped.length() - 1));
	}

	private static String reversed(String str) 
	{
		return (new StringBuffer(str)).reverse().toString();
	}

}

Was This Post Helpful? 1
  • +
  • -

#7 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10364
  • View blog
  • Posts: 38,392
  • Joined: 27-December 08

Re: Palindrome JAVA

Posted 14 October 2010 - 05:21 PM

Probably a good idea to remove whitespace as well so "123 1" doesn't give you a false negative for "1231". Also, you should consider using StringBuilder instead of StringBuffer. They are the same thing, except StringBuffer is less efficient as it is synchronized for Thread-safety.
Was This Post Helpful? 2
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Palindrome JAVA

Posted 14 October 2010 - 05:22 PM

View Postcyberbemon, on 14 October 2010 - 04:13 PM, said:

thank you guys for your reply :)..so i edited my code and this is wat it looks like now..how ever i'm still a bit confused about the revers string.(keeping the first letter and reversing th e rest for eg.tom -> tmo.).how do i do it without an array?.@Luckless i tried to use your reverse method but i cudn;t get it to work.. :(
public class palindrome1 {
    public static void main(String[] args) 
    {
        String input = JOptionPane.showInputDialog("enter the string");//string input
        String input1 = input.toUpperCase();//converts the entered string to upper case
        for(int i = 0; i < input1.length()/2; i++){
            if (input1.charAt(i) != input1.charAt(input1.length()-1-i))
                    {
                        System.out.println("the entered string is not a palindrome");
                        break;
                    }
            else 
            {
                System.out.print("the entered string is a palindrome");
                break;
                
            }
        }
    }

}

You almost dit it ...but you cannot apply the if() else inside the loop it will break at the firs iteration whatever happens..
public class palindrome1 {
    public static void main(String[] args) 
    {
        String input = JOptionPane.showInputDialog("enter the string");//string input
        String input1 = input.toUpperCase();//converts the entered string to upper case
        boolean palin = true;
        for(int i = 0; i < input1.length()/2; i++){
            if (input1.charAt(i) != input1.charAt(input1.length()-1-i))
                    {
                        palin = false;
                        break;  // no need to continue the loop
                    }
        }
        if(palin)
           System.out.print("the entered string is a palindrome");
        else
           System.out.print("the entered string is NOT a palindrome");
 
    }

}

Was This Post Helpful? 1
  • +
  • -

#9 jimdandy75  Icon User is offline

  • D.I.C Regular

Reputation: 37
  • View blog
  • Posts: 311
  • Joined: 30-June 08

Re: Palindrome JAVA

Posted 14 October 2010 - 05:52 PM

View Postmacosxnerd101, on 14 October 2010 - 04:21 PM, said:

Probably a good idea to remove whitespace as well so "123 1" doesn't give you a false negative for "1231". Also, you should consider using StringBuilder instead of StringBuffer. They are the same thing, except StringBuffer is less efficient as it is synchronized for Thread-safety.

Good point! :smile2:
import javax.swing.JOptionPane;

public class Pali{

	public static void main (String[] args) {
		String orig = JOptionPane.showInputDialog("enter the string").toUpperCase().replace(" ", "" );//string input
		String flipped = reversed(orig).toUpperCase();

		if(orig.equals(flipped))
		System.out.println("This IS a palindrome.");
		else
		System.out.println("This IS NOT palindrome.");
		
		System.out.print(orig.charAt(0));
		System.out.print(flipped.substring(0, flipped.length() - 1));
	}

	private static String reversed(String str) 
	{
		return (new StringBuilder(str)).reverse().toString();
	}

}

Was This Post Helpful? 1
  • +
  • -

#10 cyberbemon  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 14-October 10

Re: Palindrome JAVA

Posted 16 October 2010 - 11:52 AM

thank you all for the wonderful help :).I just have one last request xD..i'm a second year IT student and this is the first time i'm using java.(i did C last year).i just want to get good at this progamming language because we'll be using java a lot.does any one know any website that has good java puzzles or exercises.is it too much to ask :D.

once again thanks a lot :)
Was This Post Helpful? 0
  • +
  • -

#11 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10364
  • View blog
  • Posts: 38,392
  • Joined: 27-December 08

Re: Palindrome JAVA

Posted 16 October 2010 - 11:55 AM

Projecteuler.net and codingbat.com are two excellent websites. Martyr2 also has an excellent project ideas list.
Was This Post Helpful? 1
  • +
  • -

#12 cyberbemon  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 14-October 10

Re: Palindrome JAVA

Posted 16 October 2010 - 12:10 PM

View Postmacosxnerd101, on 16 October 2010 - 10:55 AM, said:

Projecteuler.net and codingbat.com are two excellent websites. Martyr2 also has an excellent project ideas list.


thanks man :)
Was This Post Helpful? 0
  • +
  • -

#13 harmy01  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 15
  • View blog
  • Posts: 179
  • Joined: 15-June 10

Re: Palindrome JAVA

Posted 16 October 2010 - 12:56 PM

The following examples seems easy for me. Just push each character of String into an stack and pop them out. Stack(first in last out)


import java.util.Stack;
import java.util.PriorityQueue;
import java.util.Collections;
import java.util.List;

public class Plindrome
{
    // instance variables
     private Stack<Character> plindromeStack;
     public boolean plindromeNumber;

    /**
     * Constructor for objects of class Palindrome
     */
    public Plindrome()
    {
        // initialise instance variables
       plindromeStack = new Stack<Character>();
       plindromeNumber = false;
    }

    /**
     * checking if the series of numbers are plindrome
     */
    public String checkForPlindrome(String number)
    {
        String validPlindrome = "Not a plindrome";
        String tempPlindrome = "";
        for(int index = 0; index < number.length(); index++)
        {
          plindromeStack.push(number.charAt(index));
        }
        while(plindromeStack.size() != 0)
        {
          tempPlindrome += ""+plindromeStack.pop();
           if(tempPlindrome.equals(number))
           {
               validPlindrome = "a plindrome";
               plindromeNumber = true;
           }
        }
       return validPlindrome;
    }

 }


Was This Post Helpful? 0
  • +
  • -

#14 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Palindrome JAVA

Posted 16 October 2010 - 08:00 PM

View Postharmy01, on 16 October 2010 - 01:56 PM, said:

The following examples seems easy for me. Just push each character of String into an stack and pop them out. Stack(first in last out)


import java.util.Stack;
import java.util.PriorityQueue;
import java.util.Collections;
import java.util.List;

public class Plindrome
{
    // instance variables
     private Stack<Character> plindromeStack;
     public boolean plindromeNumber;

    /**
     * Constructor for objects of class Palindrome
     */
    public Plindrome()
    {
        // initialise instance variables
       plindromeStack = new Stack<Character>();
       plindromeNumber = false;
    }

    /**
     * checking if the series of numbers are plindrome
     */
    public String checkForPlindrome(String number)
    {
        String validPlindrome = "Not a plindrome";
        String tempPlindrome = "";
        for(int index = 0; index < number.length(); index++)
        {
          plindromeStack.push(number.charAt(index));
        }
        while(plindromeStack.size() != 0)
        {
          tempPlindrome += ""+plindromeStack.pop();
           if(tempPlindrome.equals(number))
           {
               validPlindrome = "a plindrome";
               plindromeNumber = true;
           }
        }
       return validPlindrome;
    }

 }


There are peoples who likes to complicate their life for nothing
Don't worry about them :)
@harmy01 this is obviously an homework for basic student in Java who probably does not even know what a stack is, and may be not even an Object

This post has been edited by pbl: 16 October 2010 - 08:09 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1