I use the TreeSet collection . It is possible to add no more than one entry to add. When I try to add a new one, I write what has been added, but there remains only the same record that the 1st one was added, and the size does not change.

I hope for your help.

This class contains a collection for storing data in the statement, as well as statistical methods for adding data to the collection; output data from the list to a text file; entering them into the collection from this file; output data from the list to the console.

package lr7; import java.io.*; import java.util.*; public class DataManager { private static TreeSet<Energy> lst=new TreeSet<Energy>(); public static String delimeter = "/"; static boolean tryParseInt(String value) { try { Integer.parseInt(value); return true; } catch (NumberFormatException e) { return false; } } static boolean tryParseDouble(String value) { try { Double.parseDouble(value); return true; } catch (NumberFormatException e) { return false; } } public static void Add() { Scanner sc = new Scanner(System.in); String plant, test; double cons_plan = 0; double cons_fact = 0; System.out.println("Новая запись:"); System.out.print("Введите название завода:"); plant = sc.nextLine(); System.out.print("Введите потребление энергии за планом:"); while (cons_plan == 0) { test = sc.nextLine(); if (tryParseDouble(test) && Double.parseDouble(test) > 0) cons_plan = Integer.parseInt(test); else System.out.println("Ошибка! Введите положительное число число!"); } System.out.print("Введите потребление энергии фактично:"); while (cons_fact == 0) { test = sc.nextLine(); if (tryParseDouble(test) && Double.parseDouble(test) > 0) cons_fact = Integer.parseInt(test); else System.out.println("Ошибка! Введите положительное число число!"); } lst.add(new Energy(plant, cons_plan, cons_fact)); System.out.println("Завод успешно добавлен! \n"); } public static int Delete() { Scanner sc = new Scanner(System.in); System.out.println("Введите номер записи для удаления > "); int position = sc.nextInt(); if(lst.isEmpty() || position > lst.size()) { System.out.println("Такой записи нет \uD83D\uDE48"); return 0; } lst.remove(--position); System.out.println("Запись успешно удалена!"); return 1; } public static int Clear() { lst.clear(); System.out.println("Ведомость очищена!"); return 1; } // //считаем сумму потребление электроэнергии за планом public static double calculateSumConsPlan() { double sum = 0; for (Energy i: lst) { sum += i.getCons_plan(); } return sum; } //считаем сумму фактического потребление электроэнергии public static double calculateSumConsFact() { double sum = 0; for (Energy i: lst){ sum+= i.getCons_fact();} return sum; } //строим таблицу public static void printData() { if (lst.isEmpty()) { System.out.println("Нет данных для печати! Повторите попытку."); } else { System.out.println("---------------------------------------------------------------------------"); System.out.println("| | Потребление электроэнергии, кВт/час | Отклонение от плана |"); System.out.println("| Завод |-------------------------------------|---------------------------|"); System.out.println("| | за планом | фактично | в кВт/час | в % |"); System.out.println("|-------|------------------|------------------|---------------|-----------|"); System.out.println("| Z | P | F | O1 | O2 |"); System.out.println("|-------|------------------|------------------|---------------|-----------|"); //выводим наши значения for (Energy e : lst) { System.out.format("|%1$-7s|%2$-18.2f|%3$-18.2f|%4$-15.2f|%5$-11.2f|\n", e.getPlant(), e.getCons_plan(), e.getCons_fact(), e.calculateDeviation(), e.calculateDeviation1()); System.out.println("|-------------------------------------------------------------------------|"); } System.out.format("|%1$-7s|%2$-18.2f|%3$-18.2f| | |\n","Итого", calculateSumConsPlan(), calculateSumConsFact()); System.out.println("---------------------------------------------------------------------------"); } } // public static int ReadData() { BufferedReader bR; Scanner sc = new Scanner(System.in); System.out.print("Введите имя файла > "); String fileName = sc.next(); try { FileReader fR = new FileReader("C:\\Users\\Егор\\Desktop\\" + fileName); bR = new BufferedReader(fR); } catch (IOException e) { System.out.println("Файл не найден \uD83D\uDE48"); return 0; } String line; String[] tokens; lst.clear(); try { while ((line = bR.readLine()) != null) { System.out.println(line); tokens = line.split(delimeter); lst.add(new Energy(tokens[0], Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2]))); } } catch (IOException e) { System.out.println("Ошибка чтения файла \uD83D\uDE33"); return 0; } System.out.println("Файл открыт!"); return 1; } public static int WriteData() { BufferedWriter bW; Scanner sc = new Scanner(System.in); System.out.print("Сохранить как > "); String path = sc.next(); try { FileWriter fW = new FileWriter("C:\\Users\\Егор\\Desktop\\" + path); bW = new BufferedWriter(fW); } catch (IOException e) { System.out.println("Ошибка создания файла \uD83D\uDE33"); return 0; } for (Energy item: lst ) { try { bW.write(item.getPlant() + delimeter + item.getCons_plan() + delimeter + item.getCons_fact()); bW.newLine(); } catch (IOException e) { System.out.println("Ошибка сохранения \uD83D\uDE33"); return 0; } } try { bW.close(); } catch (IOException e) { return 0; } System.out.println("Данные добавлены в файл!"); return 1; } }` 

This class is intended to describe any of the list entries:

  package lr7; import java.lang.String; public class Energy implements Comparable<Energy>{ // Поля private String plant; private double cons_plan,cons_fact; private double devidation, devidation1; //Конструктор public Energy(String plant, double cons_plan, double cons_fact) { this.plant = plant; this.cons_plan = cons_plan; this.cons_fact = cons_fact; this.devidation = this.calculateDeviation(); this.devidation1 = this.calculateDeviation1(); } //--------------------Методы start--------------------- //название завода public String getPlant() {return plant;} //потребление электроэнергии за планом public double getCons_plan() { return cons_plan; } //фактическое потребление электроэнергии public double getCons_fact() { return cons_fact; } //Отклонение от плана в кВт/час public double calculateDeviation() { return cons_plan-cons_fact; } //Отклонение от плана в % public double calculateDeviation1() { return ((cons_plan-cons_fact)*(100/cons_plan)); } @Override public int compareTo(Energy o) { return 0; } //--------------------Методы end--------------------- } 

This is the class containing the main program method:

  package lr7; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String command; label: while (true) { System.out.println("Чтобы добавить данные о новом заводе введите \"1\""); System.out.println("Чтобы вывести данные на экран введите \"2\""); System.out.println("Чтобы записать данные в файл введите \"3\""); System.out.println("Чтобы считать данные с файла введите \"4\""); System.out.println("Чтобы удалить запись введите \"5\""); System.out.println("Чтобы очистить все данные введите \"6\""); System.out.println("Чтобы выйти программы введите \"0\":"); command = sc.nextLine(); switch (command) { case "1": DataManager.Add(); break; case "2": DataManager.printData(); break; case "3": DataManager.WriteData(); break; case "4": DataManager.ReadData(); break; case "5": DataManager.Delete(); break; case "6": DataManager.Clear(); break; case "0": break label; default: System.out.println("Неизвестная команда!"); break; } } } } 

    1 answer 1

    Set is a collection that contains unique objects. That is, by adding a regular element to the Set , a check is performed to see if such an element is already there. In TreeSet uniqueness is determined using the Comparable interface, which contains the compareTo method. You add the first element to an empty Set - the element is successfully added. You try to add a second one, when adding, compareTo is called to compare with an already added element, and your compareTo always returns 0. That is, for your TreeSet absolutely all Energy objects are equal. You need to correctly implement compareTo and everything will be fine.

    TreeSet documentation