今天就開始學習有關循環和不同類型的知識。我的問題是在這種情況下,我會嘗試使用哪種類型?和其他人相比,它有什麼優勢?看完我的講義後,似乎應該總是使用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));
}
}
[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
當你確定你想要運行一個循環的次數時,最好使用for循環,當你不想不知道你想要運行一個循環多少次,但是你知道終止它的條件,最好使用while循環。當你想至少運行一次循環時使用while。 –
我們不是來做你的功課。在提出具體問題之前,請先嚐試一下。閱讀[如何問一個好問題](https://stackoverflow.com/help/how-to-ask) – davidchoo12