2017-02-16 14 views
2

配列を作成し、配列を出力し、配列で10で割り切れるすべての数を数える3つのメソッドを作成しました。私に最も迷惑を与えている部分が10.割り切れる数字をカウントしている私がこれまで持っているコードです:配列内の10で割り切れる数え算の数

public int[] createArray(int size) { 

    Random rnd = new Random(); 
    int[] array = new int[size]; 

    for (int i = 0; i < array.length; i++) { 
     array[i] = rnd.nextInt(101); 
    } 
    return array; 
} 

public void printArray() { 

    Journal5a call = new Journal5a(); 
    int[] myArray = call.createArray(10); 

    for (int i = 0; i < myArray.length; i++) { 
     System.out.println(myArray[i]); 
    } 
    System.out.println("There are " + call.divideByTen(myArray[i]) + " numbers that are divisable by 10"); 
} 

public int divideByTen(int num) { 

    int count = 0; 

    if (num % 10 == 0) { 
     count++; 
    } 
    return count;   
} 

public static void main(String[] args) { 

    Journal5a call = new Journal5a(); 
    Random rnd = new Random(); 

    call.printArray(); 
} 
+1

アレイ全体を渡す。その後、それをループし、if条件を呼び出して最終的なカウントを返します。 –

+2

単一要素ではない完全配列を渡す – Hemal

+0

'System.out.println(" + call.divideByTen(myArray [i])+ "10で割り切れる数"); "i"は範囲外です。 –

答えて

5

は、メソッドに配列を渡し、カウントを決定するためにそれを使用。あなたのアルゴリズムは合理的に見えます。 Javaの8+で何かのように、

public int divideByTen(int[] nums) { 
    int count = 0; 
    for (int num : nums) { 
     if (num % 10 == 0) { 
      count++; 
     } 
    } 
    return count; 
} 

または、そして、あなたはprintf

System.out.println("There are " + call.divideByTen(myArray) 
     + " numbers that are divisible by 10"); 

またはのようにそれを呼び出すことができますIntStreamfilter

return (int) IntStream.of(nums).filter(x -> x % 10 == 0).count(); 

などを使用インラインのように

System.out.printf("There are %d numbers that are divisible by 10.%n", 
     IntStream.of(nums).filter(x -> x % 10 == 0).count()); 
+0

また、数値が出力されるループでは、 'total + = call.divideByTen(myArray [i]);'を追加してから 'total'を表示することもできます。ただし、新しい変数が必要になります。 –

0

このようにすることができます。完全な配列を渡し、10で除算を確認します。簡単にするために他の部分を省略しました。

public void printArray() { 

    Journal5a call = new Journal5a(); 
    int[] myArray = call.createArray(10); 

    divideByTen(myArray); 
} 

public int divideByTen(int[] num) { 

    int count = 0; 
    for(i=0;i<num.length;i++) 
    { 
     if (num[i] % 10 == 0) { 
      count++; 
     } 
    } 
    return count;   
} 
関連する問題