Coding I Consider the following method header and contract a

Coding I Consider the following method header and contract, and an implementation body taken from the previous tracing table. For this question, examples of strings that are palindromes include \"racecar\" and \"noon\", but not \"sum i am\" due to space characters./** * Reports whether a string is a palindrome. * * @ensures ispalindrome = [s reads the same way backward or forward] */Private static boolean ispalindrome (String s) {boolean ans = false; int i = 0; int r = s.length () - 1; while (i

Solution

This is the piece of code provided but this code works fine for the strings\"racecar\" and \"noon\".

But this code will not work fine for the strings \"racecmr\".if we check by passing it as input to the

piece of code.Then it returning the wrong output as true.But this the string \"racecmr\" is not palindrome.

So we have to do a small change in this code.

  private static boolean isPalindrome(String s) {

                        boolean ans=false;

                        int i=0;

                        int r=s.length()-1;

                       

                        while(i<s.length()/2)

                        {

                                    if(s.charAt(i)==s.charAt(r-i))

                                    {

                                                ans=true;

                                    }

                                    else

                                    {

ans=false; //We have to replace this statement with return false;

                                    }

                                    i=i+1;

                        }

                        return ans;

            }

}

_________________

After Modifying, the correct piece of code is :

private static boolean isPalindrome(String s) {
       boolean ans=false;
       int i=0;
       int r=s.length()-1;
      
       while(i<s.length()/2)
       {
           if(s.charAt(i)==s.charAt(r-i))
           {
               ans=true;
           }
           else
           {
               ans=false;
           }
           i=i+1;
       }
       return ans;
   }

____________Thank You

 Coding I Consider the following method header and contract, and an implementation body taken from the previous tracing table. For this question, examples of st
 Coding I Consider the following method header and contract, and an implementation body taken from the previous tracing table. For this question, examples of st

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site