String rev = new String(); for ( int j=data.length()-1; j >= 0; j-- ) rev += dat
ID: 3549084 • Letter: S
Question
String rev =
new String();
for ( int j=data.length()-1; j >= 0; j-- )
rev += data.charAt(j);
return rev;
}
public static void main ( String[] args )
{
System.out.println( reverse( "Hello" ) );
Q4. Modify ReverseTester.java to do the following:<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
(a) Ask a user to enter a string from the keyboard and then print out the reverse of the entered string.
(b) Print out the length of the string.
String lower = trial.toLowerCase();
StringBuffer azBuffer =
new StringBuffer();
for ( int j=0; j < lower.length(); j++ )
{
char c = lower.charAt(j);
if ( c >= 'a' && c <= 'z' )
azBuffer.append( c );
}
String forward = azBuffer.toString();
String backward = azBuffer.reverse().toString();
if ( forward.equals( backward ) )
return true;
else
return false;
}
}
public class PalindromeTester
{
public static void main ( String[] args )
{
Tester pTester = new Tester();
String trial = "A man, a plan, a canal, Panama!" ;
if ( pTester.test( trial ) )
System.out.println( "Is a Palindrome" );
else
System.out.println( "Not a Palindrome" );
Q5. Modify Tester.java to do the following:
(a) Ask a user to enter a phrase from the keyboard and then determine if the phrase is a palindrome or not.
(b) Print out the palindrome, all uppercase.
Explanation / Answer
// PROGRAM 1.
import java.util.*;
class reverse_string
{
public static String reverse(String data)
{
String rev = new String();
for ( int j=data.length()-1; j >= 0; j-- )
rev += data.charAt(j);
return rev;
}
public static void main ( String[] args )
{
String str;
Scanner in = new Scanner(System.in);
System.out.println("Enter String :");
str = in.next();
System.out.println("Reverse of String is " + reverse(str));
System.out.println("Length of String is " + str.length());
}
}
// PROGRAM 2.
import java.util.*;
class Tester
{
public String reverse(String data)
{
String rev = new String();
for ( int j=data.length()-1; j >= 0; j-- )
rev += data.charAt(j);
return rev;
}
public boolean test(String str)
{
return str.equalsIgnoreCase(reverse(str));
}
}
class PalindromeTester
{
public static void main ( String[] args )
{
String str;
Scanner in = new Scanner(System.in);
System.out.println("Enter String :");
str = in.next();
Tester pTester = new Tester();
String trial = "A man, a plan, a canal, Panama!" ;
if ( pTester.test( str ) )
{
System.out.println("Palindrome Is " + str );
System.out.println("Is a Palindrome" );
}
else
System.out.println( "Not a Palindrome" );
}
}