Question 1: Comparing two String In the file Sorting.Java, write a method called
ID: 3565979 • Letter: Q
Question
Question 1: Comparing two String In the file Sorting.Java, write a method called Compare^2 that takes String s1 and String s2 as arguments and returns an integer. It should compare s1 and s2 alphabetic ally such as follows: You cannot use any built in functions^3 for comparing strings provided by Java for this question^4. You should use a for loop that compares each character one by ones. Recall that we can extract characters from Strings using the charAt method. You are to treat upper and lower case as if they were identical^6.Explanation / Answer
import java.string;
class Sorting{
public integer Compare(String s1, String s2){
int i;
int s1length=0,s2length=0;
for(i=0;s1.charAt(i)!=NULL;i++) //length of s1 in s1length
s1length++;
for(i=0;s2.charAt(i)!=NULL;i++) //length of s2 in s2length
s2length++;
if(s1length>s2length) //if both strings lengths are not equal
return 1;
else if(s1length<s2length)
return -1;
s1.toUpperCase();
s2.toUpperCase();
for(i=0;i<s1length;i++){
if(s1.charAt(i)>s2.charAt(i))
return 1;
else if(s1.charAt(i)<s2.charAt(i))
return -1;
}
return 0;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.