好吧,我已經在很長一段時間了。我在堆棧溢出處理過類似的問題,但仍然無法工作。我需要在數組中找到最大值和最小值。試圖找到最小的問題。我已經literately從編寫單獨的方法都試過了等等,仍然在0以下的輸出是我曾嘗試:for循環中的Java數組最小元素
import java.util.Scanner;
class ArrayMin {
public static void main(String args[]) {
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int a[] = new int[10];
int max = a[0];
int min = a[0];
System.out.println("Enter elements of array :");
for (int i = 0; i < 10; i++) {
a[i] = scanner.nextInt();
if (i == 9)
break;
}
for (int i = 1; i < a.length; i++) {
if (a[i] > max)
max = a[i];
else if (a[i] < min)
min = a[i];
}
System.out.println("Result is max is :" + (max)); //if I input 1-10, output is 10
System.out.println("Result is min is :" + (min)); //whatever number I input the output is always 0
}
}
使用調試器要經過你的代碼一步一步應該很快給你答案...... – assylias
初始化分鐘爲0。因此,如果從'[1-10]'最小總會你輸入號碼也是0.也可以刪除for循環中的if。 –
'if(i == 9)break;'是多餘的。如果你把它拿出來,'i'會增加到10,然後循環將退出,因爲'i <10'條件不再成立。這是你想要的。 – ajb