1 int stringCompare(String str1, String str2) Description: Given two Strings, co
ID: 3688890 • Letter: 1
Question
1 int stringCompare(String str1, String str2) Description: Given two Strings, compare the value of hte strings. If the first comes earlier than the second, then return EXACTLY -1; if it comes later than the second, then return EXACTLY +1; if they are equal, then return zero. 4 Input: str1-the first string str2 the second string Output: 1, 0, or 1, depending on the comparison of the Strings. Hint There is a String method to compare two Strings. You are encouraged to use it! However, you won't be able to return its value directly, since it returns many different positive and negative numbers. You are only allowed to return -1,0,1.Explanation / Answer
1..
class CompareStrings
{
int stringCompare(String str1,String str2)
{
if ( str1.compareTo(str2) > 0 )
return 1;
else if ( str1.compareTo(str2) < 0 )
return -1;
else
return 0;
}
public static void main(String args[])
{
String str1, str2;
CompareStrings CS= new CompareStrings();
Scanner in = new Scanner(System.in);
System.out.println("Enter the first string");
str1 = in.nextLine();
System.out.println("Enter the second string");
str2 = in.nextLine();
System.out.println(CS.stringCompare(str1,str2));
}
}
2..
int arrayAvg(int[] values){
int sum = 0;
for(int i=0; i < numbers.length ; i++)
sum = sum + numbers[i];
double average = sum / numbers.length;
}
3.
public class PosorNeg {
boolean isPositive(int x){
if(x>=0)
return Positive;
else
return Negative;
}
public static void main(String[] args) {
System.out.println("5 is " + isPositive(5));
System.out.println("-8 is " + isPositive(-8));
}
}
4.
boolean arrayAllNonNeg(int[] nums)
{
for (int i = 0; i < nums.length; i++) {
if(nums[i]<0)
return false;
}
return true;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.