diff --git a/out/production/JavaCore/homeworks/homework01/Fahrenheit.class b/out/production/JavaCore/homeworks/homework01/Fahrenheit.class new file mode 100644 index 0000000..867477c Binary files /dev/null and b/out/production/JavaCore/homeworks/homework01/Fahrenheit.class differ diff --git a/out/production/JavaCore/homeworks/homework01/Task2.class b/out/production/JavaCore/homeworks/homework01/Task2.class new file mode 100644 index 0000000..b35daed Binary files /dev/null and b/out/production/JavaCore/homeworks/homework01/Task2.class differ diff --git a/out/production/JavaCore/homeworks/homework02/Task2.class b/out/production/JavaCore/homeworks/homework02/Task2.class new file mode 100644 index 0000000..81107c9 Binary files /dev/null and b/out/production/JavaCore/homeworks/homework02/Task2.class differ diff --git a/out/production/JavaCore/homeworks/homework02/Task3.class b/out/production/JavaCore/homeworks/homework02/Task3.class new file mode 100644 index 0000000..00b9c18 Binary files /dev/null and b/out/production/JavaCore/homeworks/homework02/Task3.class differ diff --git a/out/production/JavaCore/homeworks/homework07/App.class b/out/production/JavaCore/homeworks/homework07/App.class new file mode 100644 index 0000000..50f43b0 Binary files /dev/null and b/out/production/JavaCore/homeworks/homework07/App.class differ diff --git a/out/production/JavaCore/homeworks/homework07/DiscountProduct.class b/out/production/JavaCore/homeworks/homework07/DiscountProduct.class new file mode 100644 index 0000000..19b03e0 Binary files /dev/null and b/out/production/JavaCore/homeworks/homework07/DiscountProduct.class differ diff --git a/out/production/JavaCore/homeworks/homework07/Person.class b/out/production/JavaCore/homeworks/homework07/Person.class new file mode 100644 index 0000000..1581cbc Binary files /dev/null and b/out/production/JavaCore/homeworks/homework07/Person.class differ diff --git a/out/production/JavaCore/homeworks/homework07/Product.class b/out/production/JavaCore/homeworks/homework07/Product.class new file mode 100644 index 0000000..61fcb11 Binary files /dev/null and b/out/production/JavaCore/homeworks/homework07/Product.class differ diff --git a/out/production/JavaCore/homeworks/homework08/App.class b/out/production/JavaCore/homeworks/homework08/App.class new file mode 100644 index 0000000..2103056 Binary files /dev/null and b/out/production/JavaCore/homeworks/homework08/App.class differ diff --git a/out/production/JavaCore/homeworks/homework08/Person.class b/out/production/JavaCore/homeworks/homework08/Person.class new file mode 100644 index 0000000..8b737d7 Binary files /dev/null and b/out/production/JavaCore/homeworks/homework08/Person.class differ diff --git a/out/production/JavaCore/homeworks/homework08/Product.class b/out/production/JavaCore/homeworks/homework08/Product.class new file mode 100644 index 0000000..69d5714 Binary files /dev/null and b/out/production/JavaCore/homeworks/homework08/Product.class differ diff --git a/output.txt b/output.txt new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/homeworks/homework01/Fahrenheit.java b/src/main/java/homeworks/homework01/Fahrenheit.java new file mode 100644 index 0000000..19af621 --- /dev/null +++ b/src/main/java/homeworks/homework01/Fahrenheit.java @@ -0,0 +1,12 @@ +package homeworks.homework01; + +public class Fahrenheit { + public static void main(String[] args) { + double fahrenheit = 212.0; + double celsius = (fahrenheit - 32) * 5/9; { + + System.out.println(fahrenheit + " "+"градусов" + " " +"по Фаренгейту"+" равна"+ " "+ celsius + " по Цельсию"); + } + } + } + diff --git a/src/main/java/homeworks/homework03/App.java b/src/main/java/homeworks/homework03/App.java new file mode 100644 index 0000000..69cf7e7 --- /dev/null +++ b/src/main/java/homeworks/homework03/App.java @@ -0,0 +1,47 @@ +package homeworks.homework03; + +import java.util.Random; +import java.util.Scanner; + +public class App { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + Random random = new Random(); + + // объект Television с случайными параметрами + Television tv = createTelevision(scanner, random); + + System.out.println("Созданный телевизор: " + tv); + + // Изменение параметров телевизора + tv.setColor("Silver"); + tv.setMark("LG"); + tv.setVolt(110); + + System.out.println("Обновленный телевизор: " + tv); + + Television tv1 = createTelevision(scanner, random); + Television tv2 = createTelevision(scanner, random); + Television tv3 = createTelevision(scanner, random); + + System.out.println("Созданный телевизор 1: " + tv1); + System.out.println("Созданный телевизор 2: " + tv2); + System.out.println("Созданный телевизор 3: " + tv3); + + } + + public static Television createTelevision(Scanner scanner, Random random) { + + System.out.print("Введите цвет телевизора: "); + String color = scanner.nextLine(); + + System.out.print("Введите марку телевизора: "); + String mark = scanner.nextLine(); + + // Генерация случайного напряжения от 100 до 240 + Integer volt = random.nextInt(141) + 100; + + // экземпляр телевизора + return new Television (color, mark, volt); + } + } diff --git a/src/main/java/homeworks/homework03/Television.java b/src/main/java/homeworks/homework03/Television.java new file mode 100644 index 0000000..3e97b6c --- /dev/null +++ b/src/main/java/homeworks/homework03/Television.java @@ -0,0 +1,47 @@ +package homeworks.homework03; + +public class Television { + public static void main(String[] args) { + } + + private Integer volt; // Напряжение + private String color; // Цвет + private String mark; // Марка + + // Конструктор по умолчанию + public Television () { + this.color = "Black"; + this.mark = "LG"; + this.volt = 240; + } + + // Конструктор с параметрами + public Television(String color, String mark, Integer volt ) { + this.color = color; + this.mark = mark; + this.volt = volt; + + } + + // Методы-сеттеры + public void setColor(String color) { + this.color = color; + } + + public void setMark(String mark) { + this.mark = mark; + } + + public void setVolt(Integer volt) { + this.volt = volt; + } + + @Override + public String toString() { + return "Television{" + + "volt=" + volt + + ", color='" + color + '\'' + + ", mark='" + mark + '\'' + + '}'; + } + } \ No newline at end of file diff --git a/src/main/java/homeworks/homework04/Alfavit.java b/src/main/java/homeworks/homework04/Alfavit.java new file mode 100644 index 0000000..0c89589 --- /dev/null +++ b/src/main/java/homeworks/homework04/Alfavit.java @@ -0,0 +1,25 @@ +package homeworks.homework04; + +import java.util.Scanner; + + public class Alfavit { + public static void main(String[] args) { + String alphabet = "qwertyuiopasdfghjklzxcvbnm"; + Scanner scanner = new Scanner(System.in); + System.out.print("Введите маленькую букву английского алфавита: "); + char inputChar = scanner.next().charAt(0); + + // маленькая буква + if (alphabet.indexOf(inputChar) == -1) { + System.out.println("введите маленькую букву английского алфавита."); + } else { + int index = alphabet.indexOf(inputChar); + // замкнутость + int leftIndex = (index - 1 + alphabet.length()) % alphabet.length(); + // Получаем букву слева + char leftChar = alphabet.charAt(leftIndex); + System.out.println("Буква слева: " + leftChar); + } + } + } + diff --git a/src/main/java/homeworks/homework04/Arrows.java b/src/main/java/homeworks/homework04/Arrows.java new file mode 100644 index 0000000..a171c8a --- /dev/null +++ b/src/main/java/homeworks/homework04/Arrows.java @@ -0,0 +1,26 @@ +package homeworks.homework04; + +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + public class Arrows { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + System.out.println("Введите строку со стрелами: "); + String input = scanner.nextLine(); + + Pattern pattern = Pattern.compile(">>-->|<--<<"); + + + Matcher matcher = pattern.matcher(input); + + int counter = 0; + + while (matcher.find()) { + counter++; + } + System.out.println("Количество найденных стрел: " + counter); + } + } + diff --git a/src/main/java/homeworks/homework06/java/App.java b/src/main/java/homeworks/homework06/java/App.java new file mode 100644 index 0000000..a3f2dc4 --- /dev/null +++ b/src/main/java/homeworks/homework06/java/App.java @@ -0,0 +1,170 @@ +package homeworks.homework06.java; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +class Product { + private String name; + private double price; + + public Product(String name, double price) { + if (name == null || name.trim().isEmpty()) { + throw new IllegalArgumentException("Название продукта не может быть пустым"); + } + if (price < 0) { + throw new IllegalArgumentException("Стоимость продукта не может быть отрицательной"); + } + this.name = name; + this.price = price; + } + + public String getName() { + return name; + } + + public double getPrice() { + return price; + } + + @Override + public String toString() { + return name + " (Цена: " + price + " рублей)"; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + Product product = (Product) obj; + return Double.compare(product.price, price) == 0 && name.equals(product.name); + } + + @Override + public int hashCode() { + return 31 * name.hashCode() + Double.hashCode(price); + } +} + +class Person { + private String name; + private double money; + private List basket; + + public Person(String name, double money) { + if (name == null || name.trim().isEmpty()) { + throw new IllegalArgumentException("Имя не может быть пустым"); + } + if (money < 0) { + throw new IllegalArgumentException("Деньги не могут быть отрицательными"); + } + this.name = name; + this.money = money; + this.basket = new ArrayList<>(); + } + + public String getName() { + return name; + } + + public double getMoney() { + return money; + } + + public List getBasket() { + return basket; + } + + public boolean buyProduct(Product product) { + if (product.getPrice() <= money) { + basket.add(product); + money -= product.getPrice(); + System.out.println(name + " купил " + product.getName()); + return true; + } else { + System.out.println(name + " не может позволить себе " + product.getName()); + return false; + } + } + + @Override + public String toString() { + return name + (basket.isEmpty() ? " - Ничего не куплено" : " - " + basket); + } +} + +public class App { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + List customers = new ArrayList<>(); + List products = new ArrayList<>(); + + customers.add(new Person("Павел Андреевич", 10000)); + customers.add(new Person("Анна Петровна", 2000)); + customers.add(new Person("Борис", 10)); + + products.add(new Product("Хлеб", 40)); + products.add(new Product("Молоко", 60)); + products.add(new Product("Торт", 1000)); + products.add(new Product("Кофе растворимый", 879)); + products.add(new Product("Масло", 150)); + + // Процесс выбора продуктов + int currentCustomerIndex = 0; + + while (true) { + Person currentCustomer = customers.get(currentCustomerIndex); + System.out.println(currentCustomer.getName() + ", выберите продукт (или введите 'END' для завершения):"); + for (Product product : products) { + System.out.println(product); + } + + String input = scanner.nextLine(); + if (input.equalsIgnoreCase("END")) { + break; + } + + // Найти выбранный продукт + boolean productFound = false; + for (Product product : products) { + if (product.getName().equalsIgnoreCase(input)) { + currentCustomer.buyProduct(product); + productFound = true; + break; + } + } + + if (!productFound) { + System.out.println("Продукт не найден. Попробуйте снова."); + } +// Переход к следующему покупателю + currentCustomerIndex = (currentCustomerIndex + 1) % customers.size(); + } + + // Вывод содержимого пакета для каждого покупателя + for (Person customer : customers) { + System.out.println(customer); + } + + // Обработка случаев + testAdditionalCases(scanner); + } + + private static void testAdditionalCases(Scanner scanner) { + // Тестовые случаи + try { + Person zhenya = new Person("Женя", 0); + Product iceCream = new Product("Мороженое", 200); + zhenya.buyProduct(iceCream); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + + try { + Person sveta = new Person("Света", -3); + Product pasta = new Product("Макароны", 800); + sveta.buyProduct(pasta); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + } +} diff --git a/src/main/java/homeworks/homework07/App.java b/src/main/java/homeworks/homework07/App.java new file mode 100644 index 0000000..22bee84 --- /dev/null +++ b/src/main/java/homeworks/homework07/App.java @@ -0,0 +1,228 @@ +package homeworks.homework07; + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; +import java.time.LocalDate; + +class Product { + private String name; + private double price; + + public Product(String name, double price) { + if (name == null || name.trim().isEmpty() || name.matches("\\d+") || name.length() < 3) { + throw new IllegalArgumentException("Недопустимое имя продукта!"); + } + if (price <= 0) { + throw new IllegalArgumentException("Стоимость продукта должна быть положительной!"); + } + this.name = name; + this.price = price; + } + + public String getName() { + return name; + } + + public double getPrice() { + return price; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + Product product = (Product) obj; + return Double.compare(product.price, price) == 0 && name.equals(product.name); + } + + @Override + public String toString() { + return "Product{" + + "name='" + name + '\'' + + ", price=" + price + + '}'; + } + + @Override + public int hashCode() { + return 31 * name.hashCode() + Double.hashCode(price); + } +} + +class DiscountProduct extends Product { + private double discount; // Размер скидки + private LocalDate expirationDate; // Срок действия скидки + + public DiscountProduct(String name, double price, double discount, LocalDate expirationDate) { + super(name, price); + if (discount <= 0 || discount >= price) { + throw new IllegalArgumentException("Скидка должна быть положительной и меньше цены продукта."); + } + this.discount = discount; + this.expirationDate = expirationDate; + } + + @Override + public double getPrice() { + if (LocalDate.now().isAfter(expirationDate)) { + return super.getPrice(); // Возвращаем обычную цену, если срок действия скидки истек + } + return super.getPrice() - discount; // Возвращаем цену со скидкой + } + + @Override + public String toString() { + return super.toString() + " (Скидка: " + discount + " рублей, Срок действия: " + expirationDate + ")"; + } +} + +class Person { + private String name; + private double money; + private List basket; + + public Person(String name, double money) { + if (name == null || name.trim().isEmpty()) { + throw new IllegalArgumentException("Имя не может быть пустым"); + } + if (money < 0) { + throw new IllegalArgumentException("Деньги не могут быть отрицательными"); + } + this.name = name; + this.money = money; + this.basket = new ArrayList<>(); + } + + public String getName() { + return name; + } + + public double getMoney() { + return money; + } + + public List getBasket() { + return basket; + } + + public boolean buyProduct(Product product) { + if (product.getPrice() <= money) { + basket.add(product); + money -= product.getPrice(); + System.out.println(name + " купил " + product.getName()); + return true; + } else { + System.out.println(name + " не может позволить себе " + product.getName()); + return false; + } + } + + @Override + public String toString() { + return name + (basket.isEmpty() ? " - Ничего не куплено" : " - " + basket); + } +} + +public class App { + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + List customers = new ArrayList<>(); + List products = new ArrayList<>(); + + customers.add(new Person("Павел Андреевич", 10000)); + customers.add(new Person("Анна Петровна", 2000)); + customers.add(new Person("Борис", 10)); + + products.add(new Product("Хлеб", 40)); + products.add(new Product("Молоко", 60)); + products.add(new DiscountProduct("Торт", 1000, 200, LocalDate.now().plusDays(5))); // Скидка 200 + products.add(new DiscountProduct("Кофе растворимый", 879, 432, LocalDate.now().plusDays(3))); // Скидка 432 + products.add(new Product("Масло", 150)); + + // Процесс выбора продуктов + int currentCustomerIndex = 0; + + while (true) { + Person currentCustomer = customers.get(currentCustomerIndex); + System.out.println(currentCustomer.getName() + ", выберите продукт (или введите 'END' для завершения):"); + for (Product product : products) { + System.out.println(product); + } + + String input = scanner.nextLine(); + if (input.equalsIgnoreCase("END")) { + break; + } + + // Найти выбранный продукт + boolean productFound = false; + for (Product product : products) { + if (product.getName().equalsIgnoreCase(input)) { + currentCustomer.buyProduct(product); + productFound = true; + break; + } + } + + if (!productFound) { + System.out.println("Продукт не найден. Попробуйте снова."); + } + + // Переход к следующему покупателю + currentCustomerIndex = (currentCustomerIndex + 1) % customers.size(); + } + + // Вывод содержимого пакета для каждого покупателя + for (Person customer : customers) { + System.out.println(customer); + } + + // Обработка случаев + testAdditionalCases(scanner); + } + + private static void testAdditionalCases(Scanner scanner) { + // Тестовые случаи + try { + Person zhenya = new Person("Женя", 0); + Product iceCream = new Product("Мороженое", 200); + zhenya.buyProduct(iceCream); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + + try { + Person sveta = new Person("Света", -3); + Product pasta = new Product("Макароны", 800); + sveta.buyProduct(pasta); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } + + // Тестирование недопустимых имен и цен + try { + Product invalidProduct1 = new Product("88", 100); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); // Недопустимое имя продукта! + } + + try { + Product invalidProduct2 = new Product("Т", 100); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); // Недопустимое имя продукта! + } + + try { + Product invalidProduct3 = new Product("Шоколадка", -1); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); // Стоимость продукта должна быть положительной! + } + + try { + DiscountProduct invalidDiscountProduct = new DiscountProduct("Чипсы", 100, 150, LocalDate.now().plusDays(5)); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); // Скидка должна быть положительной и меньше цены продукта. + } + } +} diff --git a/src/main/java/homeworks/homework08/App.java b/src/main/java/homeworks/homework08/App.java new file mode 100644 index 0000000..3dd9923 --- /dev/null +++ b/src/main/java/homeworks/homework08/App.java @@ -0,0 +1,164 @@ +package homeworks.homework08; + + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +class Product { + private String name; + private double price; + + public Product(String name, double price) { + if (name == null || name.trim().isEmpty()) { + throw new IllegalArgumentException("Название продукта не может быть пустым"); + } + if (price < 0) { + throw new IllegalArgumentException("Стоимость продукта не может быть отрицательной"); + } + this.name = name; + this.price = price; + } + + public String getName() { + return name; + } + + public double getPrice() { + return price; + } +} + +class Person { + private String name; + private double money; + private List basket; + + public Person(String name, double money) { + if (name == null || name.trim().isEmpty()) { + throw new IllegalArgumentException("Имя не может быть пустым"); + } + if (money < 0) { + throw new IllegalArgumentException("Деньги не могут быть отрицательными"); + } + this.name = name; + this.money = money; + this.basket = new ArrayList<>(); + } + + public String getName() { + return name; + } + + public double getMoney() { + return money; + } + + public List getBasket() { + return basket; + } + + public boolean buyProduct(Product product) { + if (product.getPrice() <= money) { + basket.add(product); + money -= product.getPrice(); + return true; + } else { + return false; + } + } + + @Override + public String toString() { + if (basket.isEmpty()) { + return name + " - Ничего не куплено"; + } + StringBuilder result = new StringBuilder(name + " - "); + for (Product product : basket) { + result.append(product.getName()).append(", "); + } + return result.substring(0, result.length() - 2); + } +} + +public class App { + public static void main(String[] args) { + List customers = new ArrayList<>(); + List products = new ArrayList<>(); + List outputMessages = new ArrayList<>(); + + // Считывание данных из файла с использованием BufferedReader + try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) { + // Считывание покупателей + String line = br.readLine(); + String[] customerData = line.split("; "); + for (String data : customerData) { + String[] parts = data.split(" = "); + String name = parts[0]; + double money = Double.parseDouble(parts[1]); + customers.add(new Person(name, money)); + } + + // Считывание продуктов + line = br.readLine(); + String[] productData = line.split("; "); + for (String data : productData) { + String[] parts = data.split(" = "); + String name = parts[0]; + double price = Double.parseDouble(parts[1]); + products.add(new Product(name, price)); + } + + // Считывание покупок + while ((line = br.readLine()) != null) { + if (line.equals("END")) { + break; + } + String[] parts = line.split(" "); + String customerName = parts[0]; + String productName = parts[1]; + + // Поиск покупателя и продукта + Person customer = customers.stream() + .filter(c -> c.getName().equals(customerName)) + .findFirst() + .orElse(null); + Product product = products.stream() + .filter(p -> p.getName().equals(productName)) + .findFirst() + .orElse(null); + + // Пытаемся купить продукт + if (customer != null && product != null) { + boolean success = customer.buyProduct(product); + if (success) { + outputMessages.add(customerName + " купил " + productName); + } else { + outputMessages.add(customerName + " не может позволить себе " + productName); + } + } + } + } catch (IOException e) { + System.out.println("Ошибка при чтении файла: " + e.getMessage()); + } + + // Вывод результатов в файл + try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) { + for (String message : outputMessages) { + bw.write(message); + bw.newLine(); + } + for (Person customer : customers) { + bw.write(customer.toString()); + bw.newLine(); + } + } catch (IOException e) { + System.out.println("Ошибка при записи в файл: " + e.getMessage()); + } + } +} +