【问题标题】:Use count method and for each loop to count the number of element in the array使用 count 方法并为每个循环计算数组中元素的数量
【发布时间】:2014-10-20 04:20:04
【问题描述】:

我知道如何在没有 for each 循环的情况下计算数组中元素的数量,但我必须为此使用 for 每个循环。这就是我到目前为止所得到的。我不知道如何使用每个循环来计算数组中元素的数量。结果应该是 6。我将不胜感激。非常感谢。

public class Count{
 public Count(){
    int a[] = {7, 8, 9, 9, 8, 7};
    System.out.println(count(a));        
 }

 public int count(int count[]){
    for (int c : count)
    return c;
 }
}

【问题讨论】:

  • int counter = 0; for (int c : count) { counter++;} return counter;...?
  • 这与使用常规 for 循环是一回事。只需在循环外部初始化一个变量,在内部递增,然后在最后返回它。

标签: java arrays methods foreach count


【解决方案1】:
public int count(int count[])
{
    int i = 0;
    for (int c : count) {
        i++;
    }
    return i;
}

这将为数组中的每个元素将i 增加 1,并最终返回 i,这将是 6(在您的情况下)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多