2017-01-17 63 views
0

我阅读了有关foreach循环的内容,并试图找到Array中最大的元素,但它不像平常那​​样工作。我想知道有什么区别?使用foreach循环查找数组中最大的元素

public void foreachloop() 
{ 
    int[] T = { 1, 2, 3, 4, 5, 6, 7 }; 
    int x = T[0]; 

    for (int element : T) { 
     if (T[element] > x) { 
      x = T[element]; 
     } 
    } 

    System.out.println(x); 
} 
+1

'element'表示数组的整个元素,而不是它的指数 – Andrew

+1

'如果(元素> x)x =元素;' –

+0

好吗谢谢! – qargul

回答

2

当你做for (int element: T),可变element贯穿在T每个值。所以你不应该试图看看价值T[element] - 只是element本身。

像这样:

for (int element: T) { 
    if (element > x) x = element; 
} 

如果尝试访问T[element]element是7,将抛出一个异常,因为7是不是你的阵列的有效指标。 (有效指数是0〜6)

1

当您使用的foreach,必须首先定义什么是数组(这里是int),那么你给出一个arbitary名(您选择element),然后:类型,然后是数组的名称。之后,您可以使用您选择的名称访问元素。

public void foreachloop() 
{ 
    int[] T = { 1, 2, 3, 4, 5, 6, 7 }; 
    int x = T[0]; 

    for (int element : T) { 
     if (element > x) { 
      x = element; 
     } 
    } 

    System.out.println(x); 
} 
2
  1. 初始化max是最小的整数可能
  2. 使用,如果当前元素是for-each循环检查比max大,如果是这样做出的max新值
  3. 返回max在for-each循环完成后

我个人会为此创建一个单独的方法:

import java.util.Arrays; 

class Main { 
    public static void main(String[] args) { 
    int[] arr = new int[]{1,2,3}; 
    System.out.println("The array looks like: " + Arrays.toString(arr)); //The array looks like: [1, 2, 3] 
    System.out.println("The max of the array is: " + arrayMax(arr)); //The max of the array is: 3 
    } 

    public static int arrayMax (int[] arr) { 
    int max = Integer.MIN_VALUE; //initilize max to the smallest integer possible 
    for(int element: arr) 
     max = Math.max(max, element); 
    return max; 
    } 
} 

试试吧here!

相关问题