Write a complete method including header that takes two Strings as arguments and
ID: 3575035 • Letter: W
Question
Write a complete method including header that takes two Strings as arguments and returns true if the second string is the same as the first string but in reverse! OR Option 2 (minus 1.5 marks for this option): do the same task but return true if the two strings have exactly the same characters. For either option, your solution must use loops to do the work, your method must be reasonably efficient by ending as early as possible and charAt (i) might be helpful. Complete only one option. Do not do both options.Explanation / Answer
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
class StringTest
{
public static boolean StringReverseCompare(String string1, String string2)
{
String string2reverse = "";
int length1 = string1.length();
int length2 = string2.length();
/* Check if both have same length or not, if not same then string1 and reverse of string2 cannot be equal */
if(length1 != length2)
return false;
else
{
// Compute reverse of string2
for ( int i = length1 - 1 ; i >= 0 ; i-- )
string2reverse = string2reverse + string2.charAt(i);
/* Compare string1 and reverse of string2, checking each character */
for ( int i = 0; i<length1 - 1 ; i++ )
if(string1.charAt(i) != string2reverse.charAt(i))
return false;
}
return true;
}
public static boolean StringCompare(String string1, String string2)
{
int length1 = string1.length();
int length2 = string2.length();
/* Check if both have same length or not, if not same then string1 and reverse of string2 cannot be equal */
if(length1 != length2)
return false;
else
{
/* Compare string1 and reverse of string2, checking each character */
for ( int i = 0; i<length1 - 1 ; i++ )
if(string1.charAt(i) != string2.charAt(i))
return false;
}
return true;
}
public static void main (String[] args)
{
String string1, string2 ;
Scanner in = new Scanner(System.in);
System.out.println("Enter the first string");
string1 = in.nextLine();
System.out.println("Enter the second string");
string2 = in.nextLine();
System.out.println(StringReverseCompare(string1, string2));
System.out.println(StringCompare(string1, string2));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.