簡體   English   中英

Java基本數組錯誤

[英]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

由於標准代碼Aa之前,因此以下行:

System.out.println(Arrays.asList(a2z(new String[]{"X","c","b","d"})));

將打印

[X, c, b, d]

因為X是按字母順序排列的第一個元素(因此,將在XX之間進行交換)。

如果要獲得以下輸出:

[b, c, X, d]

您需要在比較中使用compareToIgnoreCase

if (min.compareToIgnoreCase(a[i]) > 0 )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM