我基本上已经完成了这段代码,但我有一个小问题。
我的任务是编写一个名为a2z的方法,它接受一个字符串数组作为参数。此方法搜索array以查找在按a- to -z对此数组进行排序时应该是第一个元素的元素。找到此元素后,此方法应将此元素与数组的第一个元素交换。
这是我的代码:
public static void a2z(String [] a){
String min = a[0];
String temp = a[0];
for(int i = 0; i < a.length; i++){
if(a[i].compareTo(a[i+1]) <0 ){
min = a[i];
}else{
if(a[i].compareTo(a[i+1]) >0 ){
min = a[i+1];
}
}
min = a[0];
temp = a[/*index of min*/];
} 我的问题是,我应该如何找到min的索引,这样我才能使temp等于它?
编辑:我试过了
public static void a2z(String [] a){
String min = a[0];
String temp = a[0];
int indexOfMin = -1;
for(int i = 0; i < a.length; i++){
if(a[i].compareTo(a[i+1]) <0 ){
min = a[i];
indexOfMin = i;
}else{
if(a[i].compareTo(a[i+1]) >0 ){
min = a[i+1];
indexOfMin = i;
}
}
}
a[0] = min;
temp = a[i];仍然不起作用
发布于 2016-01-24 07:02:00
跟踪一路上使用的索引,并在min更新时对其进行更新。
例如:
int indexOfMin = -1;
// later...
min = a[i];
indexOfMin = i;讲得通?
发布于 2016-01-24 07:17:43
试试这个:
public static void main(String[] args) {
// just a trick to avoid iterating and printing (do not use it if the argument is null)
System.out.println(Arrays.asList(a2z(new String[]{"x","c","b","d"})));
}
// I've also changed the method type (to avoid printing in it)
public static String[] a2z(String[] a) {
// be cautious - java.lang.ArrayIndexOutOfBoundsException is ugly
if ( a == null || a.length == 0 ) {
return a;
}
// consider that the first element is the "minimum"
String min = a[0];
int minIndex = 0;
// start with 1 in for, because the first element was already considered
for (int i = 1; i < a.length; i++) {
if (min.compareTo(a[i]) > 0 ) {
// update the minimum in every step and update its position
min = a[i];
minIndex = i;
}
}
// change the first element with the "minimum" element
String temp = a[0];
a[0] = a[minIndex];
a[minIndex] = temp;
return a;
}输出
[b, c, x, d]Obs
因为有the standard codes,所以A在a之前,所以下面这行代码:
System.out.println(Arrays.asList(a2z(new String[]{"X","c","b","d"})));将打印
[X, c, b, d]因为X是按字母顺序排列的第一个元素(因此,将在X和X之间进行交换)。
如果您想要获得以下输出:
[b, c, X, d]您需要在比较中使用compareToIgnoreCase:
if (min.compareToIgnoreCase(a[i]) > 0 )https://stackoverflow.com/questions/34969992
复制相似问题