English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Thanks to Zhen Zhen for a better solution to my program.
It runs, but doesn't print the right info. There is something else not right about the program. What else could I do to fix this?

import java.util.*;
import java.io.*;


public class PalindromeTester
{
public static void main (String [] args)
{
Scanner scan=new Scanner (System.in);
String input;

System.out.print ("Enter a text");

input=scan.next();

Palindrome obj=new Palindrome (input);

boolean isP=obj.isPalindrome();
System.out.println ("your word is Palindrome:"+isP);
}
}


class Palindrome {


private String word;

public Palindrome (String word)
{
this.word=word;
}

public boolean isPalindrome() {
String temp = "";

for(int i=word.length()-1; i!=0; i--) {
temp += word.charAt(i);
}

return ( temp.equalsIgnoreCase(word) );
}

}

2007-11-15 15:17:40 · 3 answers · asked by Anonymous in Computers & Internet Programming & Design

3 answers

OOps! Let me try again... maybe try this:

public boolean isPalindrome() {
String temp = "";

for(int i=word.length()-1; i!=0; i--) {
temp += word.charAt(i);
}

if( temp.equalsIgnoreCase(word) )
return true;
else
return false;
}

}

2007-11-15 16:07:50 · answer #1 · answered by zhen zhen 2 · 0 0

I understand this is not JAVA, but i do have a sweet spot for Palindromes, after all, they are the only thing that can be both even and odd at the same time :) Here is a VB.NET solution that i just wrote, perhaps you can adapt my method to JAVA.

Private Function IsThisStringAPalidrome(ByVal Input As String) As Boolean
'The trivial solutions.
If Input.Length = 0 Or Input Is Nothing Then
IsThisStringAPalidrome = False
Exit Function
End If
If Input.Length = 1 Then
IsThisStringAPalidrome = True
Exit Function
End If

Dim I As Integer
IsThisStringAPalidrome = True
Dim ChecksRequired As Integer = 0
Dim TestString As String = Me.TextBox1.Text
Dim TestStringLen As Integer = Len(TestString)

If Math.Round(TestStringLen / 2) = TestStringLen / 2 Then
'THE STRING IS EVEN
ChecksRequired = TestStringLen / 2
Else
'THE STRING IS ODD, there will be a single character left in the middle.
ChecksRequired = (TestStringLen - 1) / 2
End If

For I = 0 To ChecksRequired - 1
Dim LChar As String = Mid(Input, I + 1, 1)
Dim RChar As String = Mid(Input, TestStringLen - I, 1)
If LChar.ToLower <> RChar.ToLower Then
IsThisStringAPalidrome = False
End If
Next
'At this point, the varirable 'IsThisStringAPalidrome' is true if the string is a palindrome, if false then it is not.
End Function

2007-11-15 16:03:04 · answer #2 · answered by SnowXNinja 3 · 0 0

In your very last for loop, the condition should be

i >= 0

instead of

i != 0

Try it!

2007-11-15 16:05:21 · answer #3 · answered by jgoulden 7 · 0 0

fedest.com, questions and answers