0

I have a Java Assignment where I have to prompt for a line input, check if its a palindrome and then say if the palindrome is made of all text, all numbers, or mixed. I haven't added the part where I check what kind of palindrome it is yet, but I need help with the code to check if it's a palindrome. The code I posted below recognizes everything as a palindrome even if it isn't. This is basic Java so I'm limited to what I used below.

import java.util.Scanner;

public class Project4{

public static void main (String [] args)
{
    String line = getInputLine();
    while (!isEmptyLine (line))
    {
        if (isPalindrome (line))
            System.out.println ("\"" + line + "\" is a palindrome.");
        else
            System.out.println ("\"" + line + "\" is not a palindrome");
            line = getInputLine();

    }
    System.out.println ("End of program");
}
public static String getInputLine ( )
{
    Scanner in = new Scanner(System.in);
    System.out.print("Enter a line of input: ");
    String inputline = in.nextLine();
    return inputline;
}
public static boolean isEmptyLine(String str)
{
    boolean truefalse;
    if(str.length()==0)
        truefalse = true;
    else
        truefalse = false;
    return truefalse;
}
public static boolean isPalindrome(String str)
{
    int left = 0;
    int right = str.length();
    boolean okay = true;
    char ch1; char ch2;

    while(okay && left<right)
    {
        ch1 = str.charAt(left);
        if(!Character.isDigit(ch1)||!Character.isLetter(ch1))
            left++;
        else
        {
            ch2 = str.charAt(right);
            if(!Character.isDigit(ch2)||!Character.isLetter(ch2))
                right--;
            else
            {
                ch1 = Character.toUpperCase(ch1);
                ch2 = Character.toUpperCase(ch2);
                if(ch1==ch2)
                {
                    left++;
                    right--;
                }
                else
                    okay = false;
            }
        }
    }
    return okay;
}
}

3 Answers3

0

You need to do logical AND of the 2 checks instead of OR -

if(!Character.isDigit(ch1) && !Character.isLetter(ch1))
sray
  • 584
  • 3
  • 8
0

Use a method like the following:

boolean isPalindrome (String input) {
    int strLength = input.length;
    for (int i=0; i < input.length/2; ++i) {
        if (input.charAt(i) != input.charAt(strLength-i)) {
            return false;
        }
    }

    return true;
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

A late answer although it might help some in the future. The method posted below doesn't use any of StringBuilder functions.

public boolean isPalindrome(String value) {
    boolean isPalindrome = true;
    for (int i = 0 , j = value.length() - 1 ; i < j ; i ++ , j --) {
        if (value.charAt(i) != value.charAt(j)) {
            isPalindrome = false;
        }
    }
    return isPalindrome;
}
capt.swag
  • 10,335
  • 2
  • 41
  • 41