Can someone help me solve this? We have data for two users, A and B, each with a
ID: 3640184 • Letter: C
Question
Can someone help me solve this?We have data for two users, A and B, each with a String name and an int id. The goal is to order the users such as for sorting. Return -1 if A comes before B, 1 if A comes after B, and 0 if they are the same. Order first by the string names, and then by the id numbers if the names are the same. Note: with Strings str1.compareTo(str2) returns an int value which is negative/0/positive to indicate how str1 is ordered to str2 (the value is not limited to -1/0/1). (On the AP, there would be two User objects, but here the code simply takes the two strings and two ints directly. The code logic is the same.)
userCompare("bb", 1, "zz", 2) ? -1
userCompare("bb", 1, "aa", 2) ? 1
userCompare("bb", 1, "bb", 1) ? 0
This is all I have so far..
public int userCompare(String aName, int aId, String bName, int bId) {
}
Explanation / Answer
The function compareToIgnoreCase() has been used to compare strings ignoring the case....:)..
import java.util.Scanner;
public class stringCompare
{
public static int userCompare(String a1,int a2,String b1, int b2)
{
int a=a1.compareToIgnoreCase(b1);
if (a>0)return 1;
else if(a<0) return -1;
else if(a==0) {
if(a2>b2) return 1;
else if(a2<b2)return -1;
else if(a2==b2) return 0;
}
return 0;
}
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
Scanner t = new Scanner(System.in);
String s1,s2;
int id1,id2,r;
System.out.println("Enter the name for A");
s1=s.nextLine();
System.out.println("Enter the id for A");
id1=s.nextInt();
System.out.println("Enter the name for B");
s2=t.nextLine();
System.out.println("Enter the id for B");
id2=t.nextInt();
r = userCompare(s1,id1,s2,id2);
System.out.println(r);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.