2017-10-10 28 views
-3

今天就開始學習有關循環和不同類型的知識。我的問題是在這種情況下,我會嘗試使用哪種類型?和其他人相比,它有什麼優勢?看完我的講義後,似乎應該總是使用do-while,但我確信情況並非如此。何時使用,while或do-while循環/如何啓動

另外我將如何開始第一個關於返回「給定數組」的總和。給定的數組是什麼?這是否就是我應該插入到運行參數行?

public class SumMinMaxArgs { 
    // TODO - write your code below this comment. 
    // You will need to write three methods: 
    // 
    // 1.) A method named sumArray, which will return the sum 
    //  of the given array. If the given array is empty, 
    //  it should return a sum of 0. 
    // 
    // 2.) A method named minArray, which will return the 
    //  smallest element in the given array. You may 
    //  assume that the array contains at least one element. 
    //  You may use your min method defined in lab 6, or 
    //  Java's Math.min method. 
    // 
    // 3.) A method named maxArray, which will return the 
    //  largest element in the given array. You may 
    //  assume that the array contains at least one element. 
    //  You may use your max method defined in lab 6, or 
    //  Java's Math.max method. 
    // 





    // DO NOT MODIFY parseStrings! 
    public static int[] parseStrings(String[] strings) { 
     int[] retval = new int[strings.length]; 
     for (int x = 0; x < strings.length; x++) { 
      retval[x] = Integer.parseInt(strings[x]); 
     } 
     return retval; 
    } 

    // DO NOT MODIFY main! 
    public static void main(String[] args) { 
     int[] ints = parseStrings(args); 
     System.out.println("Sum: " + sumArray(ints)); 
     System.out.println("Min: " + minArray(ints)); 
     System.out.println("Max: " + maxArray(ints)); 
    } 
} 
+0

[while and do while](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html)和[for循環](https://docs.oracle.com/javase/教程/ JAVA/nutsandbolts/for.html)。閱讀描述,你會發現他的邏輯非常不同。另一個主要是迭代(「主要」,因爲你最終可以做到你想做的事情) – AxelH

+0

當你確定你想要運行一個循環的次數時,最好使用for循環,當你不想不知道你想要運行一個循環多少次,但是你知道終止它的條件,最好使用while循環。當你想至少運行一次循環時使用while。 –

+0

我們不是來做你的功課。在提出具體問題之前,請先嚐試一下。閱讀[如何問一個好問題](https://stackoverflow.com/help/how-to-ask) – davidchoo12

回答

0

四種中的Java支持的循環:

  1. C風格循環:for (int i = 0 ; i < list.size() ; ++i) { ... }當你想直接訪問某些類型的列表或數組的索引,或者多次做手術。

  2. 的foreach循環,當你要遍歷一個集合,但不關心指數:for (Customer c : customers) { ... }

  3. 循環:while (some_condition) { ... }當一些代碼必須只要執行爲條件是真的。如果條件爲假,則塊內的代碼(即括號內)將不會執行。

  4. 做而循環:do { statement1; } while (condition);將執行語句1即使條件爲假開始,但它這樣做只有一次。

+0

** 1。**被稱爲_for statement_和** 2。**可以被稱爲增強語句_或簡單地_for語句_。技術上,即使它們提供相同的行爲也沒有循環。 [源](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html) – AxelH

+0

我會稱他們爲「1.請儘可能避免這個醜陋的聲明」和「2.請考慮'Stream.forEach()'「如果塊中有單個語句。 – tiktak

+0

我忘了提及所有這些語句都可以使用'while'來重寫。通常在沒有do-while的語言中,可以使用'func(); while(cond){func(); }' – tiktak

1

這三種形式都具有完全相同的表現力。你在某種情況下使用什麼取決於風格,習慣和便利。這很像你可以用不同的英語句子表達同樣的意思。

也就是說,do - while主要用於循環應至少運行一次(即只在第一次迭代後檢查條件)。

for主要用於迭代某些集合或索引範圍時。