Good day. There is the following task: The first line in the file contains a number denoting the length of the array. The second line contains the values ​​of the array. These values ​​need to fill our array. The problem arose with the filling of the array. How to implement this?

import java.io.*; public class taskTWO { public static void main(String[] args) throws Exception { double result = 0; //побочная переменная BufferedReader input = new BufferedReader(new FileReader("C:\\input.txt")); //Файл для чтения PrintWriter writer = new PrintWriter(new FileWriter("C:\\output.txt")); //Файл для записи //Читаем длину массива и создаем сам массив int length = Integer.parseInt(input.readLine()); int mass[] = new int[length]; //Считываем вторую строку и заполняем String[] split = input.readLine().split(" "); //Дальше следует заполнение массива, которое, как выяснилось, в корне неверное for (String tmp : split) { for (int i = 0; i < mass.length; i++) { mass[i] = Integer.parseInt(tmp); } } //Выполняем алгоритм для побочной задачи for(int tmp : mass) { result += (tmp/2) / mass.length; } writer.print(result); input.close(); writer.close(); } } 

    2 answers 2

    Let's look at your nested for loop.

    According to your logic, you start filling in the mass array with the value from parse for each line from the resulting array of split strings. Finally it will be filled with the last value.

    You have done n * n actions, although this is done in n.

    There will be enough to walk once, and the result is calculated here:

     for (int i = 0; i < mass.length; i++) { mass[i] = Integer.parseInt(split[i]); result += (tmp/2) / mass.length; } 

      In stream api this is implemented rather trivially:

        Integer[] array = Files //читаем из файла .lines(Paths.get("input.txt")) //пропускаем первую строку .skip(1) //разбиваем строки на слова .flatMap(str -> Stream.of(str.split(" "))) //преобразуем слова в числа .map(Integer::parseInt) //пакуем все это в массив .toArray(Integer[]::new);