-6
import java.util.Scanner;

public class palindrome{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        String rev;
        for(int i=str.length()-1,k=0;i>=0 && k<str.length();i--,k++)
        {
            rev.charAt(k) = str.charAt(i);
        }
        if(rev==str)
        System.out.println("string is palidrome");
        else
        System.out.println("string is not palindrome");
    }
}

what is wrong with this code? note: error is showing at the following line of code rev.charAt(k)=str.charAt(i);

  • 3
    `charAt(k)` is a method call. `=` is the assignment operator. You can't assign to a method call. It looks like you meant `==`, but then you still are not accomplishing anything with the comparison. – khelwood Sep 17 '20 at 14:17
  • "error is showing"... What error? Error messages contain useful information that give you a hint about what's wrong. Carefully read and try to understand the error message. And if you post a question here, at least include the error message, which makes it easier to help. – Jesper Sep 17 '20 at 14:19
  • What you have given has several java syntax errors. I suggest spending some time reading java syntax tutorials, such as this great one from oracle: https://docs.oracle.com/javase/tutorial/getStarted/index.html – McKay M Sep 17 '20 at 14:19
  • Have a look at `StringBuilder`. – Henry Sep 17 '20 at 14:20
  • 2
    Something else that's wrong with your code is `if(rev==str)` - this does not compare strings properly. See: [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Jesper Sep 17 '20 at 14:20

2 Answers2

0

.charAt(k) doesn't return a location, it only tells you what character is there.

Bryan
  • 159
  • 10
0

Sample code for palindrome program


import java.util.*; 

class PalindromeExample2  
{  
   public static void main(String args[])  
   {  
      String original, reverse = ""; // Objects of String class  
      Scanner in = new Scanner(System.in);   
      System.out.println("Enter a string/number to check if it is a palindrome");  
      original = in.nextLine();   
      int length = original.length();   
      for ( int i = length - 1; i >= 0; i-- )  
         reverse = reverse + original.charAt(i);  
      if (original.equals(reverse))  
         System.out.println("Entered string/number is a palindrome.");  
      else  
         System.out.println("Entered string/number isn't a palindrome.");   
   }  
} 
LalithK90
  • 960
  • 7
  • 15