Essays.club - Получите бесплатные рефераты, курсовые работы и научные статьи
Поиск

Потоки ввода вывода

Автор:   •  Октябрь 7, 2022  •  Лабораторная работа  •  6,236 Слов (25 Страниц)  •  141 Просмотры

Страница 1 из 25

Министерство образования Республики Беларусь

Учреждение образования

БЕЛОРУССКИЙ ГОСУДАРСТВЕННЫЙ УНИВЕРСИТЕТ

ИНФОРМАТИКИ И РАДИОТЕХНИКИ

Факультет компьютерного проектирования

Кафедра проектирования информационно-компьютерных систем

ОТЧЁТ

По лабораторной работе №3

на тему

Потоки ввода вывода

по дисциплине «ООПиП»

Выполнил студент:                                                        Бобров Д.С.

Проверил:                                                                        Куприянов Н.И.

Минск 2022

Вариант 1

  • Реализовать обработку исключительных ситуаций посредством блоков кода try() {} catch{}. Обязательно должны быть обработаны исключения типа IOException и производные от него.
  • Организовать чтение/запись в файл основных типа(ов) данных из л.р. №1 (тип должен быть контейнером других типов, содержать у себя в качестве поле другие типы/список других типов). Запись и чтение в файл осуществляется через сериализацию/десериализацию объектов. Пользовательские типы, являющиеся полями объекта, должны реализовывать интерфейс Serializable.  Для записи объектов в поток необходимо использовать класс ObjectOutputStream. После этого достаточно вызвать метод writeObject(Object ob) этого класса для сериализации объекта ob и пересылки его в выходной поток данных. Для чтения используется соответственно класс ObjectInputStream и его метод readObject(), возвращающий ссылку на класс Object. После чего следует преобразовать полученный объект к нужному типу.

Класс main()

package com.company;

import
java.util.ArrayList;
import
java.util.InputMismatchException;
import
java.util.List;
import
java.util.Scanner;

public class
Main {
   
//свойства класса
   
static Bouquet bouquet;
   static
ArrayList <ProstoClass> prostoClassArrayList = new ArrayList<>();

   
//точка входа выполнения программы(метод,с которого начинают выполняться все действия)
   
public static void main(String[] args) {


bouquet = new Bouquet();

       
String[] options = {
               
"1- Add Green house flower ",
               
"2- Add Out door flower",
               
"3- Add accessory",
               
"4 - Sort flowers by freshness",
               
"5- Print all flowers and accessory from Bouquet ",
               
"6 - Search by length",
               
"7 - Count total price",
               
"8 - Load data",
               
"9 - Save data",
               
"0- Exit",
       
};
       
Scanner scanner = new Scanner(System.in);// класс Scanner подключается к источнику данных: System.in  для ввода данных из консоли
       
int option = 1;
       while
(option != 0) {
           
printMenu(options);
           try
{
               option = scanner.nextInt()
;
               switch
(option) {
                   
case 1:
                       
addFlower_GreenHouseFlower(scanner);
                       break;
                   case
2:
                     
addFlower_OutDoorFlower(scanner);
                       break;
                   case
3:
                       
addAccessories(scanner);
                       break;
                   case
4:
                       
sortFlowers();
                       break;
                   case
5:
                       
printBouquet();
                       break;
                   case
6:
                       
searchByLength(scanner);
                       break;
                   case
7:
                       
countTotalPrice();
                       break;
                   case
8:
                       
bouquet = SaveSystem.loadData();
                       break;
                   case
9:
                       SaveSystem.
save(bouquet);
                       break;
                   case
0:
                       
exit();
               
}
           }
           
catch (InputMismatchException e)
           {
               System.
out.println("!!!ВВЕДИТЕ КОРРЕКТНОЕ ЗНАЧЕНИЕ!!!");
               
scanner.nextLine();
           
}
           
catch (Exception ex) {
               System.
out.println(ex.getMessage());

               
System.out.println("Please enter an integer value between 0 and " + (options.length - 1));
//            scanner.nextInt();
           
}
       }
       scanner.close()
;// закрытие потока
   
}
   
public static void printMenu(String[] options) {
       
// Оператор for-each перебирает все элементы массива(option - элемент массива)
       
for (String option : options) {
           System.
out.println(option);
       
}
       System.
out.print("Choose your option : ");
   
}
   
//Добавление цветка из GreenHouseFlower
   
private static void addFlower_GreenHouseFlower(Scanner scanner) {
       System.
out.println("Adding a flower ");
       
System.out.println(" Enter kind ");
       
String kind = scanner.next();
       
System.out.println(" Enter price ");
       double
price = 0;
       while
(true) {
           
try {
               price = scanner.nextInt()
;
               if
(price > 1000) {
                   
throw new BigPriceException();
               
}
               
break;
           
}
           
catch (InputMismatchException e)
           {
               System.
out.println("Введите корректное значние!");
               
scanner.nextLine();
           
}
           
catch (BigPriceException e) {
               System.
out.println(e.getMessage());
           
}
       }
       System.
out.println(" Enter length ");
       int
length = 0;
       while
(true) {
           
try {
               length = scanner.nextInt()
;
               if
(length > 100) {
                   
throw new LongLengthAnException();
               
}
               
break;
           
}
           
catch (InputMismatchException e)
           {
               System.
out.println("Введите корректное значние!");
               
scanner.nextLine();
           
}
           
catch (LongLengthAnException e) {
               System.
out.println(e.getMessage());
           
}
       }
       
boolean freshness = false;
       
System.out.println(" Enter freshness ");
       while
(true) {
           
try {
               freshness = scanner.nextBoolean()
;
               break;
           
} catch (Exception e) {
               System.
out.println("Введите корректное значение!!!");
               
scanner.nextLine();
           
}
       }


       System.
out.println(" Enter temperature ");
       int
temperature = 0;
       while
(true) {
           
try {
               temperature = scanner.nextInt()
;
               if
(temperature > 25) {
                   
throw new HighTemperatureAnException();
               
}
               
break;
           
}
           
catch (InputMismatchException e)
           {
               System.
out.println("Введите корректное значние!");
               
scanner.nextLine();
           
}
           
catch (HighTemperatureAnException e) {
               System.
out.println(e.getMessage());
           
}
       }

       Flower flower =
new GreenHouseFlower(kind, price, length, freshness, temperature);

       
bouquet.addFlower(flower);
   
}

   
//Добавление цветка из OutDoorFlower
   
private static void addFlower_OutDoorFlower (Scanner scanner)throws Exception {
       System.
out.println(" Adding a flower ");
       
System.out.println(" Enter kind ");
       
String kind = scanner.next();
       
System.out.println(" Enter price ");
       double
price = 0;
       while
(true) {
           
try {
               price = scanner.nextInt()
;
               if
(price > 1000) {
                   
throw new BigPriceException();
               
}
               
break;
           
}
           
catch (InputMismatchException e)
           {
               System.
out.println("Введите корректное значние!");
               
scanner.nextLine();
           
}
           
catch (BigPriceException e) {
               System.
out.println(e.getMessage());
           
}
       }
       System.
out.println(" Enter length ");
       int
length = 0;
       while
(true) {
           
try {
               length = scanner.nextInt()
;
               if
(length > 100) {
                   
throw new LongLengthAnException();
               
}
               
break;
           
}
           
catch (InputMismatchException e)
           {
               System.
out.println("Введите корректное значение!");
               
scanner.nextLine();
           
}
           
catch (LongLengthAnException e) {
               System.
out.println(e.getMessage());
           
}
       }

       
boolean freshness = false;
       
System.out.println(" Enter freshness ");
       while
(true) {
           
try {
               freshness = scanner.nextBoolean()
;
               break;
           
} catch (Exception e) {
               System.
out.println("Введите корректное значение!!!");
               
scanner.nextLine();
           
}
       }
       System.
out.println(" Enter lifespan ");
       int
lifespan = scanner.nextInt();

       
Flower flower = new OutDoorFlower(kind, price, length, freshness, lifespan);
     
//  Flower flower1 = new Flower();
       
bouquet.addFlower(flower);
   
}

   
//Добавление акссесуара
   
private static void addAccessories (Scanner scanner){
       System.
out.println(" Enter Accessory ");
       
System.out.println(" Enter name ");
       
String name = scanner.next();
       
System.out.println(" Enter price ");
       double
price = 0;
       while
(true) {
           
try {
               price = scanner.nextInt()
;
               if
(price > 1000) {
                   
throw new BigPriceException();
               
}
               
break;
           
}
           
catch (InputMismatchException e)
           {
               System.
out.println("Введите корректное значние!");
               
scanner.nextLine();
           
}
           
catch (BigPriceException e) {
               System.
out.println(e.getMessage());
           
}
       }

       Accessory accessory =
new Accessory(name, price);

       
bouquet.addAccessory(accessory);
   
}

   
//Cортировка по свежести
 
private static void sortFlowers () {
       System.
out.println("Flower sort started");
       
List<Flower> flowerList1 = new ArrayList<>();
       for
(Flower flower : bouquet.getFlowerList()) {
           
if (flower.isFreshness() == true) {
               flowerList1.add(flower)
;
           
}
       }
       
for (Flower flower : bouquet.getFlowerList()) {
           
if (flower.isFreshness() != true) {
               flowerList1.add(flower)
;
           
}
       }
       System.
out.println("Sorting is complete");
       
System.out.println(flowerList1);
       
bouquet.setFlowerList(flowerList1);
   
}

//Сбор букета
   
private static void  printBouquet () {
       System.
out.println("bouquet collection has begun");
           
System.out.println("Flowers in bouquet");
           for
(Flower flower: bouquet.getFlowerList()){

               System.
out.println(flower.toString());
               
System.out.println();
           
}
       System.
out.println();
       
System.out.println("Accessories in bouquet");
       for
(Accessory accessory: bouquet.getAccessoryList()){

           System.
out.println(accessory.toString());
           
System.out.println();
       
}
   }

//Поиск по длине
   
private static void  searchByLength (Scanner scanner){
       System.
out.println("Enter number 1");
       int
number1 = scanner.nextInt();
       
System.out.println("Enter number 2");
       int
number2 = scanner.nextInt();
       int
count=0;
       for
(Flower flower: bouquet.getFlowerList()) {

           
if (flower.getLength() <= number2 && flower.getLength() >= number1)
               System.
out.println(flower.toString());
           
count++;
       
}
       
if(count == 0)
           System.
out.println("Bouquet don't has flowers.");
   
}

//Подсчёт финальной стоимости
   
private static void  countTotalPrice () {
       
double sum = 0;

       for
(Flower flower : bouquet.getFlowerList()) {
sum += flower.getPrice()
;

       
}

       
for (Accessory accessory : bouquet.getAccessoryList()) {
sum += accessory.getPrice()
;

       
}
       System.
out.println("Total price="+sum);
   
}

//Организация выхода из программы
   
private static void exit(){
       System.
out.println("***Goodbye! Come to us soon!***");
System.exit(0);
   
}
}

...

Скачать:   txt (25.1 Kb)   pdf (180.1 Kb)   docx (28.3 Kb)  
Продолжить читать еще 24 страниц(ы) »
Доступно только на Essays.club