如何将for数组转换为while

时间:2016-05-19 00:00:35

标签: while-loop

arrayCount9([1, 2, 9]) → 1
arrayCount9([1, 9, 9]) → 2
arrayCount9([1, 9, 9, 3, 9]) → 3

public int arrayCount9(int[] nums) {
  int count = 0;
  for (int i=0; i<nums.length; i++) 
   {
    if (nums[i] == 9) {// checks if nums have 9
      count++;
    }

      return count;// gives num back
                                    }

我不知道怎么把它变成循环。但我试过!! 另外我如何在main方法中声明它? 任何帮助!

while(i<nums.length) 
  { 
    if (nums[i] == 9) 
    count++; // this only counts 9s 

    i++; // you need to add this to increase your array index, otherwise 
}

2 个答案:

答案 0 :(得分:1)

您没有说出您的意思。我建议你用类似Java的东西编程。如果我正确地解释你,那么你想将你的for循环转换为while循环:

public static int arrayCount9(int[] nums) {
    int i = 0;
    int count = 0;
    while(i<nums.length) 
      { 
        if (nums[i] == 9) 
        count++; // this only counts 9s 

        i++; // you need to add this to increase your array index, otherwise 
    }
    return count;
}

public static void main(String args[]) { 
    int[] nums = {1, 9, 9, 3, 9};
    System.out.println(arrayCount9(nums)); //calls the upper method 
                                           //and prints the return value to console
}

答案 1 :(得分:0)

是的,您确实没有指定您正在使用的语言。但我的回答是关于java。

   public int arrayCount9(int[] nums) {
        int count = 0;
        int i = 0;
        while(i<nums.lenght){
            if(nums[i]==9){
                count++;
                i++;
            }
            return count;
        }
   }

在main中声明它时,就像这样:

class Sample {
    public static void main(String[] args){
        int nums[] = {1, 9, 9, 4, 8, 9};
        System.out.println(arrayCount9(nums));
    }
}