3

I am trying to write a method to see if the string is a palindrome (Words that can be spelled correctly backwards too, for example "racecar". I cant find the error so maybe another set of eyes will help. Here is the code:

public boolean isPalindrome(String str){
  numberofQuestions++;
  int n = str.length();
  for( int i = 0; i < n/2; i++ )
  if (str.charAt(i) != str.charAt(n-i-1)) return false;
  return true;
}

EDIT: Screenshot of errors:

enter image description here

Start of class:

public class Geek{
private String name;
private int numberofQuestions=0;

Final Edit: Found an extra "{" inside one of the methods. Thanks to everyone for your help!

GrIsHu
  • 29,068
  • 10
  • 64
  • 102
user2943817
  • 55
  • 2
  • 3
  • 9

5 Answers5

9

I bet it is something related to missing braces, or braces that closes the class body before starting this method definition.

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
2

The method should be fully enclosed within a class

public class Geek {
    private String name;
    private int numberofQuestions = 0;

        public boolean isPalindrome(String str) {
            numberofQuestions++;
            int n = str.length();
            for (int i = 0; i < n / 2; i++)
                if (str.charAt(i) != str.charAt(n - i - 1))
                    return false;
            return true;
        }
    }
Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

Make the isPalindrome() function static.

Here's a sample:

public class Sample {

    private static int numberofQuestions;

    public static void main(String[] args)
    {
        String str = "racecar";
        String str2 = "notpalindrome";
        boolean test = isPalindrome(str);
        boolean test2 = isPalindrome(str2);
        System.out.println(str + ": " + test);
        System.out.println(str2 + ": " + test2);
    }

    public static boolean isPalindrome(String str) {
        numberofQuestions++;
        int n = str.length();
        for (int i = 0; i < n / 2; i++)
            if (str.charAt(i) != str.charAt(n - i - 1))
                return false;
        return true;
    }
}

Output:

racecar: true
notpalindrome: false
SpringLearner
  • 13,738
  • 20
  • 78
  • 116
0

You must check your curly braces that whether it is properly ended after looping , method and class.

0

I think there is problem in curly braces. You didnt end the bracket of main class Geek{ }.

Check this:

  public class Geek 
   {
        private String name;
        private int numberofQuestions = 0;

            public boolean isPalindrome(String str) 
            {
                numberofQuestions++;
                int n = str.length();
                for (int i = 0; i < n / 2; i++)
                    if (str.charAt(i) != str.charAt(n - i - 1))
                        return false;
                return true;
            }
   }
Manish Doshi
  • 1,205
  • 1
  • 9
  • 17