簡體   English   中英

我的while循環怎么了?

[英]What am I doing wrong with my while loop?

我正在研究一個接受用戶輸入(溫度)並將其放入數組的程序。 我對必須創建的最后一種方法感到困惑。 我需要遍歷數組,並從最小到最大打印它們。 我需要使用while循環來執行此操作。

問題是我需要索引來與溫度值保持一致。 該指數代表溫度的一天。 我已經有一個方法,該方法可以找到數組中的最小值並將其與索引一起打印。

我可以使用現有的方法並在新方法中使用它嗎? 如果是這樣,我不知道如何在執行while循環時調用該方法。 我要嘗試做的是找到最低值,同時打印值和索引,然后將值更改為“未初始化”變量,以便可以找到下一個最低值,依此類推。

我的代碼“ LeastToGreatest”中的最后一個方法是嘗試執行此操作,但是它不起作用。 我一直在努力嘗試自己解決這個問題。 我不知道我需要做什么或如何組織它才能正常工作。

這是我所擁有的:

public class Weather {

static int lowestTemp;
static int lowestDay;

private static final int Uninitialized = -999;

public static void main(String[] args) {
    // TODO Auto-generated method stub

    int[] high = new int[32];


            FindLowestTempInArray(low);
    System.out.println("\n" + "The lowest low is: " + lowestTemp + " degrees." + "\n"
            + "This temperature was recorded on day: " + lowestDay);



            LeastToGreatest(low);
    System.out.println("\n" + lowestDay + "    " + lowestTemp + "\n");


    }


 public static int FindLowestTempInArray(int[] T) {
    // Returns the index of the lowest temperature in array T

    lowestTemp = Uninitialized;
    lowestDay = 0;

    for (int day = 0; day < T.length; day++) {
        if (T[day] != Uninitialized && (T[day] < lowestTemp || lowestTemp == Uninitialized)) {

            lowestTemp = T[day];
            lowestDay = day;
        }
        Arrays.asList(T).indexOf(lowestDay);
    }
    return lowestDay;

}



public static void LeastToGreatest(int[] T) {
    lowestTemp = Uninitialized;
    lowestDay = 0;

    while (lowestDay >= 0 && lowestDay <= 31) {
        for (int day = 0; day < T.length; day++) {

            if (T[day] != Uninitialized && (T[day] < lowestTemp || lowestTemp == Uninitialized)) {

                lowestTemp = T[day];
                lowestDay = day;

            }
        }

    }

    }

}

是的,您可以在此處重用其他方法。

public static void leastToGreates(int[] temps) {
    // copying the old array temps into newTempArr
    int[] newTempArr = new int[temps.length];
    for (int i = 0; i < temps.length; i++)
        newTempArr[i] = temps[i];

    int days = 0;
    while (days < temps.length) {
        int lowest = FindLowestTempInArray(newTempArr);
        if (newTempArr[lowest] > Uninitialized)
            System.out.println("temp: " + newTempArr[lowest] + ", on day: " + lowest);
        // setting the temperature of the current lowest day to "Uninitialized"
        // (so it's not the lowest temperature anymore)
        newTempArr[lowest] = Uninitialized;
        days++;
    }
}

我在這里做的是:

  • 復制溫度數組(以便能夠更改其中的值)而不會影響原始數組
  • 打印陣列中的最低溫度
  • 將該索引的溫度設置為“未初始化”
  • 重復

暫無
暫無

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

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