0

Basically, this program checks if a word (String s) is a palindrome and prints out "true" if it is and "false" if it isn't.

I am currently getting three errors: "unexpected type" at line 17, "incompatible types" at lines 30 and 32.

/**
 * @(#)palindrome.java
 *
 *
 * @author 
 * @version 1.00 2009/12/10
 */
 import java.util.*;

public class palindrome {  

    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        
        if (check(s) = true)
        {
        	System.out.println("\ntrue");
        }
        else
        {
        	System.out.println("\nfalse");
        }
        
    }
    public static boolean check(String s)
    {
    	String t, r;
    	for (int i = s.length(); i = 0; i--)
    	{
    		t = s.charAt(i);
    		r = t + r;
    	}
    	if (r == s)
    	{
    		return true;
    	}
    	else
    	{
    		return false;
    	}
    }
}
2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by kdkanishka
1

there are some errors in your program,
Line 17 : You must have a Boolean value for the condition in if statement
Line 29 : String variable r is not initialized before concatenation.
Line 30 : Logical and Syntax error in for loop ( condition must boolean val)
Line 32 : s.charAt(i); returns a char value but t is a String variable(incompatible types)
Line 35 : Since String is not a primitive data type (String is a class) you cannot use basic operators to compare String variables. You must use equals() method in such comparisons.

anyway this is the correct program, compare it with your program and understand and correct programs in your program.

import java.util.*;

public class palindrome {  

    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        
        if (check(s) == true)	// if(check(s)	also correct
        {
        	System.out.println("\ntrue");
        }
        else
        {
        	System.out.println("\nfalse");
        }
        
    }
	
    public static boolean check(String s)
    {
    	String t, r="";
    	for (int i = s.length()-1; i>=0; i--)
    	{
    		t =Character.toString( s.charAt(i));
    		r = t + r;
    	}
    	if (r.equals(s))
    	{
    		return true;
    	}
    	else
    	{
    		return false;
    	}
    }
}

Thank you.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.