2016-05-19 1 views
0
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 
            } 

Я не знаю, как превратить это в цикл. Но я попробовал !! Также как я могу объявить его в основном методе? Любая помощь!Как я могу преобразовать массив с позиции для while

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 
} 

ответ

1

Вы не сказали, на каком языке вы имеете в виду. Я предлагаю вам программировать что-то похожее на Java. Если я unterstand вас правильно, то вы хотите конвертировать для петли в петлю в то время:

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 
} 
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; 
     } 
    } 

При объявлении его в основном так же, как это:

class Sample { 
    public static void main(String[] args){ 
     int nums[] = {1, 9, 9, 4, 8, 9}; 
     System.out.println(arrayCount9(nums)); 
    } 
} 
Смежные вопросы