我正在努力完成我的任务,但我不确定如何完成它。 我的代码中有3个数组,每个数组都有名字和姓氏(姓氏在数组中的第一个名字之前)。
我应该使用哪个函数来判断字符串是否在另一个字符串之前? 我在想比较,但我不太清楚如何实现它。
到目前为止,这是我的代码:
public static void main(String[] args)
{
String[] section1 = {"Curie, Marie", "Feynman, Richard", "Germain, Sophie",
"Turing, Alan"};
String[] section2 = {"Bolt, Usain", "Graf, Steffi","Hamm, Mia"};
String[] section3 = {"Bach, Johann Sebastian", "Beethoven, Ludwig van",
"Mozart, Wolfgang Amadeus", "Schumann, Clara"};
String[] merged = mergeSortedArrays(section1, section2);
String[] merged = mergeSortedArrays(merged, section3);
for(int i = 0; i < merged.length(); i ++)
System.out.print(merged[i]);
}
//Do not change the method header
public static String[] mergeSortedArrays(String[] a1, String[] a2)
{
int i = 0, j = 0, k = 0;
while(a1[i] != null && a2[j] != null)
{
if(a1[i] "comes before" a2[j])
{
merged[k] = a1[i];
i++;
else {
merged[k] = a2[j];
j++;
}
k++;
}
return merged;
}
}
答案 0 :(得分:1)
要比较两个字符串,请使用
if(a1[i].compareTo(a2[j]) <= 0) { //Means: a1[i] <= a2[j]
System.out.println("a1[" + i + "] (" + a1[i] + ") is less-than-or-equal-to a2[" + i + "] (" + a2[i] + "));
}
或者
if(a1[i].compareTo(a2[j]) < 0) { //Means: a1[i] < a2[j]
System.out.println("a1[" + i + "] (" + a1[i] + ") is less than a2[" + i + "] (" + a2[i] + "));
}
我推荐这些评论,因为我发现compareTo
函数非常令人困惑。我必须不断提醒自己,运营商是compareTo
的“到位”。我总是这样评论。
我注意到您的代码存在一些严重问题,与字符串比较无关:
merged
函数mergeSortedArrays
ArrayIndexOutOfBoundsException
anArray.length()
不正确。消除括号。