Как найти среднее значение в массиве java
Чтобы найти среднее значение в массиве целых чисел в Java, можно использовать стримы. Преобразуем массив чисел в IntStream и найдем среднее значение:
import java.util.Arrays; int[] numbers = 1, 2, 3, 4, 5>; double average = Arrays.stream(numbers).average().getAsDouble(); System.out.println(average); // 3.0
Вычислить среднее значение всех элементов в списке в Java
В этом посте будет обсуждаться, как вычислить среднее арифметическое (среднее) всех элементов в списке в Java.
1. Использование Stream.average() метод
Если вы используете JDK версии 1.8 или выше, вы можете использовать Stream для этой тривиальной задачи. Идея состоит в том, чтобы преобразовать список в соответствующий примитивный поток, т.е. IntStream , DoubleStream , или же LongStream , и позвоните в average() метод на нем. Он возвращает необязательный параметр, описывающий среднее значение элементов в потоке, или пустой необязательный параметр, если поток пуст. Вот полный код:
Среднее арифметическое элементов массива
Создаем цикл, который генерирует элементы массивов. И генерируем числа в диапазоне от 0 до 5 включительно. Если подзабыли как генерируются числа в Java, прочитайте вот эту статью «Генерация случайных чисел в Java»
for ( int i = 0 ; i < 5 ; i ++ ) < mas1 [ i ] = ( int ) ( Math . random ( ) * 6 ) ; mas2 [ i ] = ( int ) ( Math . random ( ) * 6 ) ;
Далее выводим массивы в строку с помощью класса Arrays
System . out . println ( Arrays . toString ( mas1 ) ) ;
System . out . println ( Arrays . toString ( mas2 ) ) ;
Далее создаем переменные для хранения средних арифметических массивов
double average1 = 0 ;
double average2 = 0 ;
После этого находим сумму элементов массивов, а потом делим сумму на количество элементов для нахождения среднего арифметического
for ( int i = 0 ; i < 5 ; i ++ ) < average1 += mas1 [ i ] ; average2 += mas2 [ i ] ;
После этого сравниваем средние арифметические и выводим соответствующую фразу
if ( average1 > average1 ) <
System . out . println ( «Среднее арифметическое первого массива (» + average1 + «) больше среднего арифметического » +
«второго массива (» + average2 + «)» ) ;
> else if ( average1 < average2 ) <
System . out . println ( «Среднее арифметическое первого массива (» + average1 + «) меньше среднего арифметического » +
«второго массива (» + average2 + «)» ) ;
System . out . println ( «Средние арифметические массивов равны (» + average1 + «)» ) ;
- ← Является ли массив возрастающей последовательностью
- Создать второй массив из четных элементов первого массива →
Vladislav987 / ArrayAverageCalculator.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
| package HW_Lesson6 . MethodLevel1 ; |
| //Посчитать среднее арифметическое всех элементов массива. |
| //Использовать цикл for-each. |
| public class ArrayAverageCalculator |
| public static void main ( String [] args ) |
| int [] array = <>; |
| System . out . println ( average ( array )); |
| > |
| public static int average ( int [] array ) |
| if ( array . length <= 0 ) |
| throw new IllegalArgumentException ( «Error! array.length > 0» ); |
| > else |
| int sum = 0 ; |
| for ( int i : array ) |
| sum += i ; |
| > |
| int aver = sum / array . length ; |
| return aver ; |
| > |
| > |
| > |
| // [5, 10, 2] |
| // 5 |
| //[] |
| //Exception in thread «main» java.lang.IllegalArgumentException: Error! array.length > 0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
| package HW_Lesson6 . MethodLevel1 ; |
| //Найти последний положительный элемент в массиве. |
| // Если положительных элементов нет, вернуть минимальное значение int (Integer.MIN_VALUE) |
| public class ArrayLastPositiveFinder |
| public static void main ( String [] args ) |
| int [] array = ; |
| System . out . println ( lastPositiveElem ( array )); |
| > |
| public static int lastPositiveElem ( int [] array ) |
| int lastPositive = 0 ; |
| int count = 0 ; |
| for ( int i = 0 ; i < array . length ; i ++) |
| if ( array [ i ] > 0 ) |
| lastPositive = array [ i ]; |
| count ++; |
| > |
| if ( count <= 0 ) |
| lastPositive = Integer . MIN_VALUE ; |
| > |
| > |
| return lastPositive ; |
| > |
| > |
| // [-3, -1, 20, -2, 10, 0] |
| // 10 |
| //[-3, -1, -20, -2, -10, 0] |
| //-2147483648 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
| package HW_Lesson6 . MethodLevel1 ; |
| //Посчитать количество положительных чисел в массиве. |
| //Использовать цикл for-each. |
| public class ArrayPositivesCounter |
| public static void main ( String [] args ) |
| int [] array = ; |
| countPositives ( array ); |
| > |
| public static int countPositives ( int [] array ) |
| int count = 0 ; |
| for ( int i : array ) |
| if ( i > 0 ) |
| count ++; |
| > |
| > |
| System . out . println ( count ); |
| return count ; |
| > |
| > |
| // [-3, 0, -1, 4, -2, 5] |
| // 2 |
| //[-3, 0, -1, -4, -2, -5] |
| //0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
| package HW_Lesson6 . MethodLevel1 ; |
| //Выполнить чтение массива с консоли. |
| //Формат входных значений: |
| // |
| // |
| //Считать, что пользователь всегда вводит корректные числа. |
| import java . util . Arrays ; |
| import java . util . Scanner ; |
| public class ArrayReader |
| public static void main ( String [] args ) |
| // Вводим размер массива |
| System . out . print ( «Size: » ); |
| Scanner scan = new Scanner ( System . in ); |
| int size = scan . nextInt (); |
| // Вводим числа массива через пробел |
| Scanner str = new Scanner ( System . in ); |
| System . out . print ( «Numbers: » ); |
| String num = str . nextLine (); |
| //Создаём массив слов |
| String [] numbers = num . split ( » » ); |
| //Переводим в массив чисел |
| int [] n = new int [ size ]; |
| for ( int i = 0 ; i < numbers . length ; i ++) |
| n [ i ] = Integer . parseInt ( numbers [ i ]); |
| > |
| System . out . println ( Arrays . toString ( n )); |
| > |
| > |
| //Size: 3 |
| //Numbers: 10 30 20 |
| //[10, 30, 20] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
| package HW_Lesson6 . MethodLevel1 ; |
| //Создать массив, размером size, заполненный значениями 0, 1, 2 … (size-1). |
| import java . util . Arrays ; |
| import java . util . Scanner ; |
| public class SequenceCreator |
| public static void main ( String [] args ) |
| System . out . print ( «Enter a size of array: » ); |
| Scanner scan = new Scanner ( System . in ); |
| int size = scan . nextInt (); |
| printArray ( size ); |
| > |
| public static void printArray ( int size ) |
| if ( size < 0 ) |
| throw new IllegalArgumentException ( » Error. Size >= 0 . » ); |
| > else |
| int [] array = new int [ size ]; |
| for ( int i = 0 ; i < size ; i ++) |
| array [ i ] = i ; |
| > |
| System . out . println ( Arrays . toString ( array )); |
| > |
| > |
| > |
| //Enter a size of array: 9 |
| //[0, 1, 2, 3, 4, 5, 6, 7, 8] |
| //Enter a size of array: -3 |
| //Exception in thread «main» java.lang.IllegalArgumentException: Error. Size >= 0 . |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
| package HW_Lesson6 . MethodLevel1 ; |
| //Определить, является ли массив отсортированным по возрастанию. |
| import java . util . Arrays ; |
| public class SortedChecker |
| public static void main ( String [] args ) |
| int array [] = < 10 , 50 , 20 >; |
| System . out . println ( isSorted ( array )); |
| > |
| public static boolean isSorted ( int [] array ) |
| boolean b = true ; |
| for ( int i = 1 ; i < array . length ; i ++) |
| if ( array [ i ] < array [ i - 1 ]) |
| b = false ; |
| > |
| > |
| return b ; |
| > |
| > |
| // [10, 20, 50] |
| // true |
| // [10, 10, 10] |
| // true |
| // [10, 50, 20] |
| // false |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
| package HW_Lesson6 . MethodLevel1 ; |
| //Выполнить векторное сложение двух массивов. |
| //Необходимо создать новый массив (например, res), длина которого равна длине меньшего входного массива, |
| // и заполнить его по принципу |
| //res[i] = a[i] + b[i] |
| import java . util . Arrays ; |
| public class VectorSumCalculator |
| public static void main ( String [] args ) |
| int [] a = < 10 , 30 , 20 >; |
| int [] b = < 2 , 3 >; |
| System . out . println ( Arrays . toString ( vectorSum ( a , b ))); |
| > |
| public static int [] vectorSum ( int [] a , int [] b ) |
| int lenght ; |
| if ( a . length > b . length ) |
| lenght = b . length ; |
| > else |
| lenght = a . length ; |
| > |
| int [] res = new int [ lenght ]; |
| for ( int i = 0 ; i < lenght ; i ++) |
| res [ i ] = a [ i ] + b [ i ]; |
| > |
| return res ; |
| > |
| > |
| // [10, 30, 20], [2, 3] |
| // [12, 33] |
| //[2, 3], [10, 30, 20] |
| //// [12, 33] |
