[英]java basic array error
我已经完成了这段代码,但是有一个小问题。
我的任务是编写一个名为a2z的方法,该方法接受字符串数组作为参数。 此方法搜索数组以查找从a到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*/];
}
我的问题是我应该如何找到最小值的索引,以便使温度等于该值?
编辑:我尝试了
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];
仍然没有工作
跟踪沿途使用的索引,每当更新min
都对其进行更新。
例如:
int indexOfMin = -1;
// later...
min = a[i];
indexOfMin = i;
说得通?
尝试这个:
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 :
由于标准代码 , 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 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.