• Августа 12, 2020, 06:50:08 pm
• Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Не получили письмо с кодом активации?
Новости: Вебинар по выбору IT профессии: http://bit.ly/2S4kcC6

Автор Тема: Java OOP Alexander 07.07.2020 (Жилянская Вт-Чт)  (Прочитано 431 раз)

YuraKhomenko

  • Пользователи
  • *
  • Сообщений: 49
    • Просмотр профиля
Re: Java OOP Alexander 07.07.2020 (Жилянская Вт-Чт)
« Ответ #45 : Июля 23, 2020, 12:24:20 am »
class CopyFile


package com.gmail.yurakhomenko1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyFile {

public static void copyFile(File in, File out) throws IOException {

byte[] buffer = new byte[1000000];
int readByte = 0;

try (OutputStream fos = new FileOutputStream(out);
InputStream fis = new FileInputStream(in)) {

for (; (readByte = fis.read(buffer)) > 0;) {
fos.write(buffer, 0, readByte);
}
} catch (IOException e) {
throw e;
}
}
}



YuraKhomenko

  • Пользователи
  • *
  • Сообщений: 49
    • Просмотр профиля
Re: Java OOP Alexander 07.07.2020 (Жилянская Вт-Чт)
« Ответ #46 : Июля 23, 2020, 12:25:55 am »
class MyFileFilter


package com.gmail.yurakhomenko1;

import java.io.File;
import java.io.FileFilter;

public class MyFileFilter implements FileFilter {

private String[] arr;

public MyFileFilter() {
super();
}

public MyFileFilter(String... arr) {
super();
this.arr = arr;
}

public boolean check(String ch) {
for (String checkArr : arr) {
if (checkArr.equals(ch)) {
return true;
}
}
return false;
}

@Override
public boolean accept(File pathName) {
int pIndex = pathName.getName().lastIndexOf(".");
if (pIndex == -1) {
return false;
}
String ch = pathName.getName().substring(pIndex + 1);
return check(ch);
}

}



DenisMazur

  • Пользователи
  • *
  • Сообщений: 10
    • Просмотр профиля
    • E-mail
Re: Java OOP Alexander 07.07.2020 (Жилянская Вт-Чт)
« Ответ #47 : Июля 23, 2020, 12:46:41 am »
Домашнее задание №4
1. Усовершенствуйте класс Group, добавив возможность интерактивного добавления объекта.
package com.gmail.ua.dmazur;

public interface NewGroup {

public abstract void addNewStudent();
public abstract void delStudent(int numOfRecord);
public abstract void arraysSortSurname();
public abstract Student findStudent(String student);


}


package com.gmail.ua.dmazur;

import java.awt.HeadlessException;
import java.util.Arrays;

import javax.imageio.event.IIOReadProgressListener;
import javax.swing.JOptionPane;

import com.gmail.ua.dmazur.exceptions.NegativeValueException;
import com.gmail.ua.dmazur.exceptions.NoFreeSpaceInGroupException;
import com.gmail.ua.dmazur.exceptions.NullValueException;
import com.gmail.ua.dmazur.exceptions.WrongGroupException;
import com.gmail.ua.dmazur.exceptions.WrongNumberOfRecord;
import com.gmail.ua.dmazur.exceptions.WrongSearchOfStudentException;

public class Group implements NewGroup, Voencom {
private int currentGroup = 12;
private Student[] group = new Student[10];

public Group() {
super();
}

public Group(Student[] group) {
super();
this.group = group;
}

public Student[] getGroup() {
return group;
}

public void setGroup(Student[] group) {
this.group = group;
}

public int getCurrentGroup() {
return currentGroup;
}

public void setCurrentGroup(int currentGroup) {
this.currentGroup = currentGroup;
}

public void addStudent(Student student) {

try {
if (student.getNumberOfGroup() != getCurrentGroup()) {
throw new WrongGroupException();
}

for (int i = 0; i < group.length; i++) {
if (group[i] == null) {
group[i] = student;
System.out.println("Student " + student.getSurname() + " added to the group");
return;
}
}
throw new NoFreeSpaceInGroupException();
} catch (NoFreeSpaceInGroupException e) {

System.out.println("Student " + student.getSurname() + " " + e.getMessage());
} catch (WrongGroupException e) {
System.out.println("Student " + student.getSurname() + e.getMessage());
}

}

@Override
public void delStudent(int numOfRecord) {

try {
for (int i = 0; i < group.length; i++) {
if (group[i] != null && group[i].getNumberOfRecord() == numOfRecord) {
System.out.println("Student " + group[i].getSurname() + " whas excluded from the group");
group[i] = null;
return;
}
}
throw new WrongNumberOfRecord();
} catch (WrongNumberOfRecord e) {
System.out.println(e.getMessage());
}

}

@Override
public Student findStudent(String student) {
Student st = new Student();
try {

for (int i = 0; i < this.group.length; i++) {

if (this.group[i] == null) {
i++;
} else if (this.group[i].getSurname().equalsIgnoreCase(student)) {
// System.out.println(group[i].toString());

return st = this.group[i];
}

}
throw new WrongSearchOfStudentException();
} catch (WrongSearchOfStudentException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());

}
return st;
}

@Override
public void arraysSortSurname() {
Arrays.sort(group, new StudentSurnameComparator());

System.out.println("Surname Sort");

for (int i = 0; i < group.length; i++) {

System.out.println(group[i]);
}

}

public String totalGroup() {
String s = "";
for (int i = 0; i < group.length; i++) {
if (group[i] != null) {
s += group[i].getSurname().toString() + " " + group[i].getName().toString() + ", ";
}
}
return s;
}

@Override
public void addNewStudent() {
try {

for (int i = 0; i < group.length; i++) {
if (group[i] == null) {
Student st;
String surname;
String name;
int age = 0;
boolean sex;
int numberOfRecord = 0;
int numberOfGroup;

for (;;) {

for (;;) {
try {
surname = JOptionPane.showInputDialog("Surname:");
if (surname == null) {
throw new NullValueException("Value should be add");
}
break;

} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error number format");

} catch (HeadlessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullValueException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}

for (;;) {
try {
name = JOptionPane.showInputDialog("Name:");
if (name == null) {
throw new NullValueException("Value should be add");
}
break;

} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error number format");

} catch (HeadlessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullValueException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}

for (;;) {
try {
age = Integer.valueOf(JOptionPane.showInputDialog("Age:"));
if (age < 0) {
throw new NegativeValueException("Negative Value");
}
break;

} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error number format");

} catch (HeadlessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NegativeValueException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
for (;;) {
try {
numberOfRecord = Integer.valueOf(JOptionPane.showInputDialog("Record:"));
if (numberOfRecord < 0) {
throw new NegativeValueException("NegativeValue");
}
break;

} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error number format");

} catch (HeadlessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NegativeValueException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}

for (;;) {
try {
sex = Boolean.valueOf(JOptionPane.showInputDialog("Sex: true = Male/false = Female"));
if ( sex) {
break;
} else {
throw new NegativeValueException("true or false");
}

} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error number format");

} catch (HeadlessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NegativeValueException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}

numberOfGroup = this.getCurrentGroup();
st = new Student(surname, name, age, sex, numberOfRecord, numberOfGroup);
group[i] = st;
return;

}
}
}
throw new NoFreeSpaceInGroupException();
} catch (NoFreeSpaceInGroupException e) {
System.out.println("New student can't add " + e.getMessage());
}
}

@Override
public Student[] goToArmy() {

int n = 0;
for (int i = 0; i < group.length; i++) {
if (group[i] == null) {
i++;
} else if (group[i].getAge() >= 18 && group[i].isSex()) {
n += 1;
}

}
Student[] st = new Student[n];
int k = 0;
for (int i = 0; i < group.length; i++) {
if (group[i] == null) {
i++;
} else if (group[i].getAge() >= 18 && group[i].isSex()) {

st[k] = group[i];
k++;
}
}
return st;
}

@Override
public String toString() {
return "Group [getGroup()=" + totalGroup() + "]";
}

}


2. Реализуйте возможность сортировки списка студентов по фамилии.
Реализовал в прошлом ДЗ

3. Реализуйте возможность сортировки по параметру (Фамилия, успеваемость и т. д.).
Компараторы схожие с сортировкой по фамилии

4. Реализуйте интерфейс Военком, который вернет из группы массив студентов - юношей, которым больше 18 лет.

package com.gmail.ua.dmazur;

public interface Voencom {

public Student[] goToArmy();
}


5. Протестируйте его работу.
package com.gmail.ua.dmazur;

import java.lang.reflect.Array;
import java.util.Arrays;

public class Main {

public static void main(String[] args) {
Student student1 = new Student("Ivanov1", "Ivan1", 17, true, 10, 12);
Student student2 = new Student("Petrov2", "Ivan2", 18, true, 11, 12);
Student student3 = new Student("Ivanov3", "Ivan3", 19, false, 12, 12);
Student student4 = new Student("Petrov4", "Ivan4", 17, true, 13, 12);
Student student5 = new Student("Ivanov5", "Ivan5", 18, true, 14, 12);
Student student6 = new Student("Petrov6", "Ivan6", 19, false, 15, 13);
Student student7 = new Student("Ivanov7", "Ivan7", 17, true, 16, 12);
Student student8 = new Student("Petrov8", "Ivan8", 18, true, 17, 12);
Student student9 = new Student("Ivanov9", "Ivan9", 19, false, 18, 12);
Student student10 = new Student("Petrov10", "Ivan10", 17, true, 19, 12);
Student student11 = new Student("Ivanov11", "Ivan11", 18, true, 20, 12);
Student student12 = new Student("Petrov12", "Ivan12", 18, true, 21, 12);
Group group = new Group();

group.addStudent(student1);
group.addStudent(student2);
group.addStudent(student3);
group.addStudent(student4);
group.addStudent(student5);
group.addStudent(student6);
group.addStudent(student7);
group.addStudent(student8);
group.addStudent(student9);
group.addStudent(student10);
group.addStudent(student11);
group.addStudent(student12);

System.out.println(group);
System.out.println();
group.delStudent(19);
System.out.println();

group.addNewStudent();
System.out.println(group);
System.out.println();

group.addNewStudent();
// group.delStudent(45);
// System.out.println(group);
// group.addStudent(student12);
// System.out.println(group);
System.out.println(group.findStudent("ivanov9"));
System.out.println(group.findStudent("ivanov99"));
System.out.println();
// group.arraysSortSurname();
System.out.println(Arrays.toString(group.goToArmy()));
}

}

Andrey I

  • Пользователи
  • *
  • Сообщений: 16
    • Просмотр профиля
    • E-mail
Re: Java OOP Alexander 07.07.2020 (Жилянская Вт-Чт)
« Ответ #48 : Июля 23, 2020, 04:11:33 pm »
Дз по 5 уроку (I/O)
1. Напишите программу, которая скопирует файлы с заранее
определенным расширением(например, только doc) из
каталога источника в каталог приемник.
Main.java

package com.gmail.shaurmo;

import java.io.File;
import java.io.IOException;

public class Main {

public static void main(String[] args) {
MyFileFilter mFF = new MyFileFilter("txt");
File folderIn = new File("C:\\Users\\shaur\\Desktop");
File folderOut = new File("C:\\Users\\shaur\\Desktop\\out");
File[] fileList = folderIn.listFiles(mFF);
for (File file : fileList) {
try {
FileService.copyfile(file, new File(folderOut.getAbsolutePath() + "\\" + file.getName()), false);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}

}

}
MyFileFilter.java

package com.gmail.shaurmo;

import java.io.File;
import java.io.FileFilter;

public class MyFileFilter implements FileFilter {
private String[] arr;

public MyFileFilter(String... arr) {
super();
this.arr = arr;
}

private boolean check(String ext) {
for (String stringExt : arr) {
if (stringExt.equals(ext)) {
return true;
}
}
return false;
}

@Override
public boolean accept(File pathname) {
int pointerIndex = pathname.getName().lastIndexOf(".");
if (pointerIndex == -1) {
return false;
}
String ext = pathname.getName().substring(pointerIndex + 1);
return check(ext);
}

}

FileService.java

package com.gmail.shaurmo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileService {
public static void copyfile(File in, File out, boolean add) throws IOException {
byte[] buffer = new byte[1024];
int readByte = 0;

try (OutputStream fos = new FileOutputStream(out,add); InputStream fis = new FileInputStream(in)) {
for (; (readByte = fis.read(buffer)) > 0;) {
fos.write(buffer, 0, readByte);
}
} catch (IOException e) {
throw e;
}
}
}



2. Напишите программу, которая примет на вход два
текстовых файла, а вернет один. Содержимым этого файла
должны быть слова, которые одновременно есть и в первом и
во втором файле.
Main.java

package com.gmail.shaurmo;

import java.io.File;
import java.io.IOException;

public class Main {

public static void main(String[] args) {
File f1 = new File("C:\\Users\\shaur\\Desktop\\f1.txt");
File f2 = new File("C:\\Users\\shaur\\Desktop\\f2.txt");
File fOut = new File("C:\\Users\\shaur\\Desktop\\fOut.txt");
try {
FileService.copyCommonInFiles(f1, f2, fOut);
System.out.println("Done");
} catch (IOException e) {
System.out.println(e.getMessage());
}

}

}

FileService.java

package com.gmail.shaurmo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileService {
public static void copyCommonInFiles(File in1, File in2, File out) throws IOException {

try (BufferedReader bR = new BufferedReader(new FileReader(in1));
BufferedWriter bW = new BufferedWriter(new FileWriter(out))) {
String buf = "";
for (; (buf = bR.readLine()) != null;)
for(String str:buf.split(" ")) {
if(isThereWord(in2, str)) {
bW.write(str);
bW.write(" ");
}
}
} catch (IOException e) {
System.out.println("ERROR");
}
}
private static boolean isThereWord(File file,String str) {
try(BufferedReader bR = new BufferedReader(new FileReader(file))){
String buf="";
for (; (buf = bR.readLine()) != null;) {
for(String st:buf.split(" ")) {
if(st.equals(str)) {
return true;
}
}
}
}catch (IOException e) {
System.out.println(e.getMessage());
}
return false;
}
}

3. Усовершенствуйте класс, описывающий группу студентов,
добавив возможность сохранения группы в файл.

метод из Group.java

public void saveToCSVFile(File file) throws IOException {
String del = ";";
try (PrintWriter pw = new PrintWriter(file)) {
for (int i = 0; i < this.group.length; i++) {
if(this.group[i]!=null) {
pw.print(this.group[i].getFullName() + del);
pw.print(this.group[i].getAge() + del);
pw.print(this.group[i].getHeight() + del);
pw.print(this.group[i].getGender() + del);
pw.print(this.group[i].getRecordNumber() + del);
pw.print(this.group[i].getAverageMark() + del);
pw.print(this.group[i].getYeayOfStudy() + del);
pw.print(this.group[i].getFaculty() + System.lineSeparator());
}
}
} catch (IOException e) {
throw e;
}

}

4. Реализовать обратный процесс. Т.е. считать данные о
группе из файла, и на их основе создать объект типа группа.
метод из Group.java

public static Group readFromCSVFile(File file)throws IOException {
Group newGroup = new Group();
String del = ";";
try (BufferedReader bR = new BufferedReader(new FileReader(file))) {
String buf = "";
String[] str;
for (; (buf = bR.readLine()) != null;) {
str = buf.split(del);
String fullName = str[0];
int age = Integer.parseInt(str[1]);
int height = Integer.parseInt(str[2]);
Gender gender;
if (str[3].equals("MALE")) {
gender = Gender.MALE;
} else {
gender = Gender.FEMALE;
}
int recordNumber = Integer.parseInt(str[4]);
double averageMark = Double.parseDouble(str[5]);
int yeayOfStudy = Integer.parseInt(str[6]);
String faculty = str[7];
try {
newGroup.addStudent(new Student(fullName, age, height, gender, recordNumber, averageMark, yeayOfStudy,
faculty));
} catch (GroupOverflowException e) {
System.out.println(e.getMessage());
}
}
return newGroup;
} catch (IOException e) {
throw e;
}
}

Volodymyr A

  • Пользователи
  • *
  • Сообщений: 12
    • Просмотр профиля
    • E-mail
Re: Java OOP Alexander 07.07.2020 (Жилянская Вт-Чт)
« Ответ #49 : Июля 23, 2020, 06:06:13 pm »
1. Создайте абстрактный класс Shape, в котором есть два абстрактных метода double getPerimetr() и double getArea().
2. Создайте класс Point, в котором есть два свойства double x double y.
3. Создайте классы, которые описывают, как минимум, три геометрические фигуры (они должны быть подклассами Shape). При этом они в качестве свойств должны содержать классы Point.

Shape.java
package com.gmail.jizn.vlados;

public abstract class Shape {

    abstract double getPerimetr();
    abstract double getArea();

}

Point.java
package com.gmail.jizn.vlados;

public class Point {
    private double x;
    private double y;

    public Point() {
    }

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public double getX() {
        return x;
    }

    public void setX(double x) {
        this.x = x;
    }

    public double getY() {
        return y;
    }

    public void setY(double y) {
        this.y = y;
    }

    public static double getL(Point a, Point b) {
        return Math.sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));

    }

    @Override
    public String toString() {
        return "Point{" +
                "x=" + x +
                ", y=" + y +
                '}';
    }
}

Square.java
package com.gmail.jizn.vlados;

public class Square extends Shape {

    private Point side1;
    private Point side2;
    private Point side3;
    private Point side4;

    public Square() {
    }

    public Square(Point side1, Point side2, Point side3, Point side4) {
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
        this.side4 = side4;
    }

    public Point getSide1() {
        return side1;
    }

    public void setSide1(Point side1) {
        this.side1 = side1;
    }

    public Point getSide2() {
        return side2;
    }

    public void setSide2(Point side2) {
        this.side2 = side2;
    }

    public Point getSide3() {
        return side3;
    }

    public void setSide3(Point side3) {
        this.side3 = side3;
    }

    public Point getSide4() {
        return side4;
    }

    public void setSide4(Point side4) {
        this.side4 = side4;
    }

    @Override
    double getPerimetr() {
        double per = Point.getL(side1, side2) + Point.getL(side2, side3) + Point.getL(side3, side4) + Point.getL(side4, side1);
        return per;
    }

    @Override
    double getArea() {
        double ar = Point.getL(side1, side2) * Point.getL(side2, side3);
        return ar;
    }
}

Triangle.java
package com.gmail.jizn.vlados;

public class Triangle extends Shape {

    private Point side1;
    private Point side2;
    private Point side3;


    public Triangle() {
    }

    public Triangle(Point side1, Point side2, Point side3) {
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
    }

    public Point getSide1() {
        return side1;
    }

    public void setSide1(Point side1) {
        this.side1 = side1;
    }

    public Point getSide2() {
        return side2;
    }

    public void setSide2(Point side2) {
        this.side2 = side2;
    }

    public Point getSide3() {
        return side3;
    }

    public void setSide3(Point side3) {
        this.side3 = side3;
    }

    @Override
    double getPerimetr() {
        double per = Point.getL(side1, side2) + Point.getL(side2, side3) + Point.getL(side3, side1);
        return per;
    }

    @Override
    double getArea() {
        double halfPer = (Point.getL(side1, side2) + Point.getL(side2, side3) + Point.getL(side3, side1))/2;
        double ar = Math.sqrt(halfPer*(halfPer - Point.getL(side1,side2))*(halfPer-Point.getL(side2,side3))*(halfPer-Point.getL(side3,side1))) ;
        return ar;
    }
}

Circle.java
package com.gmail.jizn.vlados;

public class Circle extends Shape {

    private Point side1;
    private Point side2;

    public Circle() {
    }

    public Circle(Point side1, Point side2) {
        this.side1 = side1;
        this.side2 = side2;

    }

    public Point getSide1() {
        return side1;
    }

    public void setSide1(Point side1) {
        this.side1 = side1;
    }

    public Point getSide2() {
        return side2;
    }

    public void setSide2(Point side2) {
        this.side2 = side2;
    }


    @Override
    double getPerimetr() {
        double per = Point.getL(side1,side2)*2*Math.PI;
        return per;
    }

    @Override
    double getArea() {
        double ar = Point.getL(side1,side2)*Point.getL(side1,side2)*Math.PI;
        return ar;
    }
}

Main.java
package com.gmail.jizn.vlados;

public class Main {
    public static void main(String[] args) {


        Triangle triangle = new Triangle(new Point(4, 1), new Point(3, 4), new Point(2, 3));
        System.out.println(triangle);
        System.out.println(triangle.getArea());
        System.out.println(triangle.getPerimetr());

        Circle circle = new Circle(new Point(6, 14), new Point(10, 10));
        System.out.println(circle);
        System.out.println(circle.getArea());
        System.out.println(circle.getPerimetr());

        Square square = new Square(new Point(43, 74), new Point(98, 76), new Point(43, 23),
                new Point(23, 54));
        System.out.println(square);
        System.out.println(square.getArea());
        System.out.println(square.getPerimetr());

    }

}

Alexander Ts

  • Преподаватели
  • Пользователи
  • *
  • Сообщений: 13980
    • Просмотр профиля
    • E-mail
Re: Java OOP Alexander 07.07.2020 (Жилянская Вт-Чт)
« Ответ #50 : Июля 24, 2020, 11:33:35 pm »
YuraKhomenko
Решение верное

DenisMazur
Длинна метода не должна превышать 30 строк. Ваш же метод
        public void addNewStudent() {
В классе Группа гораздо длиннее. Разбейте его на подметоды.

В остальном решение верное

Andrey I
Решение верное

Volodymyr A
Решение верное

OlhaKrynytska

  • Пользователи
  • *
  • Сообщений: 20
    • Просмотр профиля
    • E-mail
Re: Java OOP Alexander 07.07.2020 (Жилянская Вт-Чт)
« Ответ #51 : Июля 27, 2020, 10:26:34 pm »
 Описать класс «Vector3d»
package vector.three.dimensional;

public class Vector {
private double x;
private double y;
private double z;

public Vector(double x, double y, double z) {
super();
this.x = x;
this.y = y;
this.z = z;
}

public synchronized double getX() {
return x;
}

public synchronized void setX(double x) {
this.x = x;
}

public synchronized double getY() {
return y;
}

public synchronized void setY(double y) {
this.y = y;
}

public synchronized double getZ() {
return z;
}

public synchronized void setZ(double z) {
this.z = z;
}

public Vector sumVector(Vector v) {
return new Vector(this.x + v.x, this.y + v.y, this.z + v.z);
}

public Vector vectProizv(Vector v) {
return new Vector(this.y * v.z - this.z * v.y, this.z * v.x - this.x * v.y, this.x * v.y - this.y * v.x);
}

public double skaliarnoeProizv(Vector v) {
double proizv = (this.x * v.x) + (this.y * v.y) + (this.z * v.z);

return proizv;
}

@Override
public String toString() {
return "Vector [x=" + x + ", y=" + y + ", z=" + z + "]";
}

}main
[code]
package vector.three.dimensional;

public class MainVector {

public static void main(String[] args) {
Vector v1 = new Vector(2, 3, 6);
Vector v2 = new Vector(6, 8, 9);
System.out.println(v1.skaliarnoeProizv(v2));
System.out.println(v1.sumVector(v2));
System.out.println(v1.vectProizv(v2));
}

}
 Создайте класс доска.

[code]

package com.gmail.koa;

import java.util.Arrays;

public class Board {
private Shape[] board = new Shape[4];

public Board(Shape[] board) {
super();
this.board = board;
}

public Shape[] getBoard() {
return board;
}

public void setBoard(Shape[] board) {
this.board = board;
}

public void addToBoard(Shape s) {
for (int i = 0; i < board.length; i++) {
if (board[i] == null) {
board[i] = s;
System.out.println(
"figure" + board[i].getClass().getSimpleName().toString() + "added to board on" + i + "place");
break;
} else if (i == board.length) {
System.out.println("все места заняты");
}
}
}

public void deleteFromBoard(int i) {
if (i > 0 && i <= board.length) {
board[i - 1] = null;
System.out.println("position" + i + "is clear");
} else {
System.out.println("нет такого места на доске");
}
}

@Override
public String toString() {
return "Board [board=" + Arrays.toString(board) + "]";
}

}
Также должен быть метод который выводит информацию о всех фигурах лежащих на  доске и их суммарную площадь.  - я не поняла как это делать

группа студентов
[code]
package com.gmail.koa;

public class Student extends Human {
private int course;
private double averageScore;
private int studentNumber;
public Student () {
super();
}


public Student(String name, String surname, int age, com.gmail.koa.sex sex, int course, double averageScore,
int studentNumber) {
super(name, surname, age, sex);
this.course = course;
this.averageScore = averageScore;
this.studentNumber = studentNumber;
}



public synchronized int getCourse() {
return course;
}



public synchronized void setCourse(int course) {
this.course = course;
}



public synchronized double getAverageScore() {
return averageScore;
}



public synchronized void setAverageScore(double averageScore) {
this.averageScore = averageScore;
}



public synchronized int getStudentNumber() {
return studentNumber;
}



public synchronized void setStudentNumber(int studentNumber) {
this.studentNumber = studentNumber;
}



@Override
public String toString() {
return "Student [course=" + course + ", averageScore=" + averageScore +
", studentNumber=" + studentNumber+ super.toString();

}


}

package com.gmail.koa;

public class Human {
private String name;
private String surname;
private int age;
private sex sex;
public Human() {
   super();
}
public Human(String name, String surname, int age, sex sex) {
   super();
   this.name = name;
   this.surname = surname;
   this.age = age;
   this.sex = sex;
}

public synchronized String getName() {
   return name;
}

public synchronized void setName(String name) {
   this.name = name;
}

public synchronized String getSurname() {
   return surname;
}

public synchronized void setSurname(String surname) {
   this.surname = surname;
}

public synchronized int getAge() {
   return age;
}

public synchronized void setAge(int age) {
   this.age = age;
}

public synchronized sex getSex() {
   return sex;
}

public synchronized void setSex(sex sex) {
   this.sex = sex;
}

@Override
public String toString() {
   return "Human [name=" + name + ", surname=" + surname + ", age=" + age + ", sex=" + sex + "]";
}





}
//enum sex {
   //male,
   //female
//}





[/code]
package com.gmail.koa;

public interface MilitaryOffice {
   public Student[] selection(Group group);
}
[/code]
package com.gmail.koa;

import java.util.Arrays;

public class MilitarySelection extends Human implements MilitaryOffice {
   private String rank;

   public MilitarySelection() {
      super();
      // TODO Auto-generated constructor stub
   }

   public MilitarySelection(String name, String surname, int age, com.gmail.koa.sex sex) {
      super(name, surname, age, sex);
      // TODO Auto-generated constructor stub
   }

   public synchronized String getRank() {
      return rank;
   }

   public synchronized void setRank(String rank) {
      this.rank = rank;
   }

   @Override
   public Student[] selection(Group group) {
      if (group == null) {
         throw new IllegalArgumentException();
      }
      Student[] students = new Student[0];
      for (int i = 0, j = 0; i < group.getGroup().length; i++) {
         if (group.getGroup() != null && group.getGroup().getSex() == sex.male
               && group.getGroup().getAge() >= 18) {
            students = Arrays.copyOf(students, students.length + 1);
            students[j] = group.getGroup();
            j++;
         }

      }
      return students;
   }

   @Override
   public String toString() {
      return "MilitarySelection [rank=" + rank + "]";
   }

}

[/code]
package com.gmail.koa;

import java.util.Comparator;

public class SortStudentsByAge implements Comparator {

@Override
public int compare(Object o1, Object o2) {
Student a1 = (Student) o1;
Student a2 = (Student) o2;
int age1 = a1.getAge();
int age2 = a2.getAge();
if (age1 > age2) {
return 1;
}
if (age1 < age2) {
return -1;
}

return 0;
}

}


[code]

package com.gmail.koa;

import java.util.Comparator;

import com.gmail.koa.Group;

public class SortStudentsBySurname implements Comparator {

@Override
public int compare(Object o1, Object o2) {
Student surnameST1 = (Student) o1;
Student surnameST2 = (Student) o2;
String surname1 = surnameST1.getSurname();
String surname2 = surnameST2.getSurname();
if (surname1.compareTo(surname2) > 0) {
return 1;
}
if (surname1.compareTo(surname2) < 0) {
return -1;
}

return 0;
}

}
[code]

package com.gmail.koa;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;

import com.gmail.koa.exceptions.ThereAreNoPlacesInGroup;

public class Group {
private Student[] group = new Student[10];

public Group() {
super();
}

public Group(Student[] group) {
super();
this.group = group;
}

public Student[] getGroup() {
return group;
}

public void setGroup(Student[] group) {
this.group = group;
}

public void addStudent(Student s) throws ThereAreNoPlacesInGroup {
for (int i = 0; i < group.length; i++) {
if (group[i] == null) {
group[i] = s;
break;
} else if (i == group.length - 1) {
throw new ThereAreNoPlacesInGroup();
}
}
return;
}

public void deleteStudentBySurname(String n) {
for (int i = 0; i < group.length; i++) {
if (n.equals(group[i].getSurname())) {
group[i] = null;
break;
}
}
return;
}

public Student searchStudent(String s) {
for (int i = 0; i < group.length; i++) {
if (s.equals(group[i].getSurname())) {
return group[i];
}
}

return null;
}

public void addStudentN() {
Scanner sc = new Scanner(System.in);
Student s = new Student();

System.out.println("write name");
s.setName(sc.nextLine());
System.out.println("write surname");
s.setSurname(sc.nextLine());
System.out.println("write age");
s.setAge(sc.nextInt());
System.out.println("write cource");
s.setCourse(sc.nextInt());
System.out.println("write average score");
s.setAverageScore(sc.nextDouble());
System.out.println("write nomber of zachotka");
s.setStudentNumber(sc.nextInt());
try {
addStudent(s);
} catch (ThereAreNoPlacesInGroup e) {
System.out.println("в группе нет мест");
}

sc.close();
}

public void safeGroupInFile(File file, String []name, String []surname, int[] age,  int[] course, double []averageScore,
int []studentNumber, String del) {
try (PrintWriter pw= new PrintWriter(file)){
for (int i = 0; i < name.length; i++) {
pw.println(name[i]+ del+surname[i] + del+ age[i]+ del
+ course[i] + del+ averageScore[i]+ del + studentNumber[i]);

}
}
catch (IOException e) {

}


}



@Override
public String toString() {
return "Group [group=" + Arrays.toString(group) + "]";
}

}
[code]
package com.gmail.koa;

import java.io.File;
import java.util.Arrays;

import com.gmail.koa.exceptions.ThereAreNoPlacesInGroup;

public class Main {

public static void main(String[] args) {

Student s = new Student("ola", "kry", 33, sex.female, 2, 3, 333);
Student s1 = new Student("oleh", "neimar", 30, sex.male, 1, 3, 888);
Student s2 = new Student("ulia", "dibrova", 31, sex.female, 5, 3, 666);
Student s3 = new Student("sasha", "kryvopustov", 18, sex.male, 5, 5, 888);
Student s4 = new Student("ulia", "sinica", 31, sex.female, 5, 9, 777);
Student s5 = new Student("slava", "potaichuk", 19, sex.male, 5, 7, 444);
Student s6 = new Student("masha", "shepetko", 31, sex.female, 5, 4, 333);
Student s7 = new Student("diana", "zushman", 31, sex.female, 5, 5, 111);
Student s8 = new Student("vlad", "vatsak", 20, sex.male, 3, 5, 222);
Student s9 = new Student("tania", "marunchin", 31, sex.female, 1, 5, 111);

Student[] stud = new Student[10];
Group g = new Group(stud);
try {
g.addStudent(s);
g.addStudent(s1);
g.addStudent(s2);
g.addStudent(s3);
g.addStudent(s4);
g.addStudent(s5);
g.addStudent(s6);
g.addStudent(s7);
g.addStudent(s8);
g.addStudent(s9);

} catch (ThereAreNoPlacesInGroup e) {
System.out.println("нет мест");
}
System.out.println(Arrays.toString(stud));
try {
g.addStudent(s1);
} catch (ThereAreNoPlacesInGroup e) {
System.out.println("нет мест");
}

Arrays.sort(stud, new SortStudentsByAge());

for (int i = 0; i < stud.length; i++) {
System.out.print(stud[i]);
System.out.println();
}

Arrays.sort(stud, new SortStudentsBySurname());
for (int i = 0; i < stud.length; i++) {
System.out.print(stud[i]);
System.out.println();
}

MilitarySelection mil = new MilitarySelection("oleh", "neimar", 18, sex.male);

mil.selection(g);
System.out.println(Arrays.toString(mil.selection(g)));

String[] name = new String[] { s.getName(), s1.getName(), s2.getName(), s3.getName(), s4.getName(),
s5.getName(), s6.getName(), s7.getName(), s8.getName(), s9.getName() };

String[] surname = new String[] { s.getSurname(), s1.getSurname(), s2.getSurname(), s3.getSurname(),
s4.getSurname(), s5.getSurname(), s6.getSurname(), s7.getSurname(), s8.getSurname(), s9.getSurname() };
int age[] = new int[] { s.getAge(), s1.getAge(), s2.getAge(), s3.getAge(), s4.getAge(), s5.getAge(),
s6.getAge(), s7.getAge(), s8.getAge(), s9.getAge() };
int cource[] = new int[] { s.getCourse(), s1.getCourse(), s2.getCourse(), s3.getCourse(), s4.getCourse(),
s5.getCourse(), s6.getCourse(), s7.getCourse(), s8.getCourse(), s9.getCourse() };
double averageScore[] = new double[] { s.getAverageScore(), s1.getAverageScore(), s2.getAverageScore(),
s3.getAverageScore(), s4.getAverageScore(), s5.getAverageScore(), s6.getAverageScore(),
s7.getAverageScore(), s8.getAverageScore(), s9.getAverageScore() };
int studentNumber[] = new int[] { s.getStudentNumber(), s1.getStudentNumber(), s2.getStudentNumber(),
s3.getStudentNumber(), s4.getStudentNumber(), s5.getStudentNumber(), s6.getStudentNumber(),
s7.getStudentNumber(), s8.getStudentNumber(), s9.getStudentNumber() };
String del = ";";
File file = new File("group.csv");
g.safeGroupInFile(file, name, surname, age, cource, averageScore, studentNumber, del);
}

}

enum sex {
male, female
}

Напишите программу, которая примет на вход два текстовых файла, а вернет один. Содержимым этого файла должны быть слова, которые одновременно есть и в первом и во втором файле (в файл записывет только первое слово, которое есть в обеих файлах, я не понимаю где ошибаюсь)

[code]
package com.gmail.oak;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
String text = "one two thee four five six,seven";
String text2 = "eight nine ten three five six";

try (FileOutputStream fos = new FileOutputStream("a.txt");
FileOutputStream fos2 = new FileOutputStream("b.txt")) {
byte[] buffer = text.getBytes();
byte[] buffer2 = text2.getBytes();
fos.write(buffer, 0, buffer.length);
fos2.write(buffer2, 0, buffer2.length);
fos.close();
fos2.close();

} catch (IOException ex) {
System.out.println(ex.getMessage());
}
System.out.println("good");

try {
String contents = readUsingScanner("a.txt");
String contents2 = readUsingScanner("b.txt");
String[] stArr;
String[] stArr2;
String razd = " ";
stArr = contents.split(razd);
stArr2 = contents2.split(razd);

for (int i = 0; i < stArr.length; i++) {
for (int j = 0; j < stArr2.length; j++) {
if (stArr[i].equals(stArr2[j])) {
FileOutputStream fos3 = new FileOutputStream("c.txt");
byte[] buffer3 = stArr[j].getBytes();
fos3.write(buffer3, 0, buffer3.length);
fos3.close();

}
}

}

} catch (IOException e) {
e.getMessage();
}

}

private static String readUsingScanner(String fileName) throws IOException {
Scanner scanner = new Scanner(Paths.get(fileName), StandardCharsets.UTF_8.name());

String data = scanner.useDelimiter("\\A").next();
scanner.close();
return data;
}
}
Напишите программу, которая скопирует файлы с заранее определенным расширением(например, только doc) из каталога источника в каталог приемник. я не поняла почему не работает
[code]
package com.gmail.koa;

import java.io.File;
import java.io.FileFilter;

public class FileFiltrDoc implements FileFilter {
private String[] arr;

public FileFiltrDoc(String... arr) {
super();
this.arr = arr;
}

private boolean check(String doc) {
for (String stringDoc : arr) {
if (stringDoc.equals(doc)) {
return true;
}
}
return false;
}

@Override
public boolean accept(File pathname) {
int pointerIndex = pathname.getName().lastIndexOf(".");
if (pointerIndex == -1) {
return false;
}
String doc = pathname.getName().substring(pointerIndex + 1);
return check(doc);

}

}
[code]
package com.gmail.koa;

import java.io.File;
import java.io.IOException;

public class Main {

public static void main(String[] args) {
FileFiltrDoc ff = new FileFiltrDoc("doc");
File f1 = new File("folderIn");
File f2 = new File("D:\\fleshka");
File[] fileArr = f2.listFiles(ff);

try {
f1.mkdir();
} catch (Exception e) {
System.out.println(e.getMessage());
}
for (int i = 0; i < fileArr.length; i++) {

try {
FileService.copyfile(file, new File(folderOut.getAbsolutePath() + "\\" + file.getName()), false);
} catch (IOException e) {
System.out.println(e.getMessage());
}

}

}

}


Alexander Ts

  • Преподаватели
  • Пользователи
  • *
  • Сообщений: 13980
    • Просмотр профиля
    • E-mail
Re: Java OOP Alexander 07.07.2020 (Жилянская Вт-Чт)
« Ответ #52 : Июля 27, 2020, 11:34:39 pm »
OlhaKrynytska
А зачем вы сделали методы классов Vector и т. д. Синхронизированными? Этого же не было в задании.

В остальном решение верное

DenisMazur

  • Пользователи
  • *
  • Сообщений: 10
    • Просмотр профиля
    • E-mail
Re: Java OOP Alexander 07.07.2020 (Жилянская Вт-Чт)
« Ответ #53 : Августа 02, 2020, 08:09:10 pm »
Домашнее задание. Урок 8
1) Используя стандартный методы сериализации создайте мини-базу данных для работы с группами студентов (возможность записи и чтения базы из файла по запросу пользователя).

Class Human
package com.gmail.ua.dmazur;

import java.io.Serializable;

public class Human implements Serializable{

private static final long serialVersionUID = 1L;
private String surname;
private String name;
private int age;
private boolean sex;

public Human() {
super();
}

public Human(String surname, String name, int age, boolean sex) {
super();
this.surname = surname;
this.name = name;
this.age = age;
this.sex = sex;
}

public boolean isSex() {
return sex;
}

public void setSex(boolean sex) {
this.sex = sex;
}

public String getSurname() {
return surname;
}

public void setSurname(String surname) {
this.surname = surname;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

@Override
public String toString() {
return "Human [surname=" + surname + ", name=" + name + ", age=" + age + ", sex=" + sex + "]";
}

}


Class Student
package com.gmail.ua.dmazur;

import java.io.Serializable;

public class Student extends Human implements Serializable{

private static final long serialVersionUID = 1L;
private int numberOfRecord;
private int numberOfGroup;

public Student() {
super();
}

public Student(String surname, String name, int age, boolean sex, int numberOfRecord, int numberOfGroup) {
super(surname, name, age, sex);
this.numberOfRecord = numberOfRecord;
this.numberOfGroup = numberOfGroup;
}

public int getNumberOfRecord() {
return numberOfRecord;
}

public void setNumberOfRecord(int numberOfRecord) {
this.numberOfRecord = numberOfRecord;
}

public int getNumberOfGroup() {
return numberOfGroup;
}

public void setNumberOfGroup(int numberOfGroup) {
this.numberOfGroup = numberOfGroup;
}

@Override
public String toString() {
return "Student [getSurname()=" + this.getSurname() + ", getName()=" + this.getName() + ", getAge()="
+ this.getAge() + ", isSex()=" + this.isSex() + ", getNumberOfGroup()=" + getNumberOfGroup()
+ ", getNumberOfRecord()=" + getNumberOfRecord() + "]";
}

}


Class Group (с разбитием на подметоды)
package com.gmail.ua.dmazur;

import java.awt.HeadlessException;
import java.io.Serializable;
import java.util.Arrays;

import javax.imageio.event.IIOReadProgressListener;
import javax.swing.JOptionPane;

import com.gmail.ua.dmazur.exceptions.NegativeValueException;
import com.gmail.ua.dmazur.exceptions.NoFreeSpaceInGroupException;
import com.gmail.ua.dmazur.exceptions.NullValueException;
import com.gmail.ua.dmazur.exceptions.WrongGroupException;
import com.gmail.ua.dmazur.exceptions.WrongNumberOfRecord;
import com.gmail.ua.dmazur.exceptions.WrongSearchOfStudentException;

public class Group implements NewGroup, Voencom, Serializable {

private static final long serialVersionUID = 1L;
private int currentGroup = 12;
private Student[] group = new Student[10];

public Group() {
super();
}

public Group(Student[] group) {
super();
this.group = group;
}

public Student[] getGroup() {
return group;
}

public void setGroup(Student[] group) {
this.group = group;
}

public int getCurrentGroup() {
return currentGroup;
}

public void setCurrentGroup(int currentGroup) {
this.currentGroup = currentGroup;
}

public void addStudent(Student student) {

try {
if (student.getNumberOfGroup() != getCurrentGroup()) {
throw new WrongGroupException();
}

for (int i = 0; i < group.length; i++) {
if (group[i] == null) {
group[i] = student;
System.out.println("Student " + student.getSurname() + " added to the group");
return;
}
}
throw new NoFreeSpaceInGroupException();
} catch (NoFreeSpaceInGroupException e) {

System.out.println("Student " + student.getSurname() + " " + e.getMessage());
} catch (WrongGroupException e) {
System.out.println("Student " + student.getSurname() + e.getMessage());
}

}

@Override
public void delStudent(int numOfRecord) {

try {
for (int i = 0; i < group.length; i++) {
if (group[i] != null && group[i].getNumberOfRecord() == numOfRecord) {
System.out.println("Student " + group[i].getSurname() + " whas excluded from the group");
group[i] = null;
return;
}
}
throw new WrongNumberOfRecord();
} catch (WrongNumberOfRecord e) {
System.out.println(e.getMessage());
}

}

@Override
public Student findStudent(String student) {
Student st = new Student();
try {

for (int i = 0; i < this.group.length; i++) {

if (this.group[i] == null) {
i++;
} else if (this.group[i].getSurname().equalsIgnoreCase(student)) {
// System.out.println(group[i].toString());

return st = this.group[i];
}

}
throw new WrongSearchOfStudentException();
} catch (WrongSearchOfStudentException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());

}
return st;
}

@Override
public void arraysSortSurname() {
Arrays.sort(group, new StudentSurnameComparator());

System.out.println("Surname Sort");

for (int i = 0; i < group.length; i++) {

System.out.println(group[i]);
}

}

public String totalGroup() {
String s = "";
for (int i = 0; i < group.length; i++) {
if (group[i] != null) {
s += group[i].getSurname().toString() + " " + group[i].getName().toString() + ", ";
}
}
return s;
}

@Override
public void addNewStudent() {
try {

for (int i = 0; i < group.length; i++) {
if (group[i] == null) {

for (;;) {

group[i] = new Student(addSurname(), addName(), addAge(), addSex(), addNumberOfRecord(),
this.getCurrentGroup());

return;

}
}
}
throw new NoFreeSpaceInGroupException();
} catch (NoFreeSpaceInGroupException e) {
System.out.println("New student can't add " + e.getMessage());
}
}

private String addSurname() {

String surname;
for (;;) {
try {
surname = JOptionPane.showInputDialog("Surname:");
if (surname == null) {
throw new NullValueException("Value should be add");
}
break;

} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error number format");

} catch (HeadlessException e) {

e.printStackTrace();
} catch (NullValueException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}

return surname;
}

private String addName() {

String name;
for (;;) {
try {
name = JOptionPane.showInputDialog("Name:");
if (name == null) {
throw new NullValueException("Value should be add");
}
break;

} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error number format");

} catch (HeadlessException e) {

e.printStackTrace();
} catch (NullValueException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
return name;
}

private int addAge() {
int age;

for (;;) {
try {
age = Integer.valueOf(JOptionPane.showInputDialog("Age:"));
if (age < 0) {
throw new NegativeValueException("Negative Value");
}
break;

} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error number format");

} catch (HeadlessException e) {

e.printStackTrace();
} catch (NegativeValueException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
return age;
}

private boolean addSex() {
boolean sex;
for (;;) {
try {
sex = Boolean.valueOf(JOptionPane.showInputDialog("Sex: true = Male/false = Female"));
if (sex) {
break;
} else {
throw new NegativeValueException("true or false");
}

} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error number format");

} catch (HeadlessException e) {

e.printStackTrace();
} catch (NegativeValueException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
return sex;
}

private int addNumberOfRecord() {
int numberOfRecord = 0;
for (;;) {
try {
numberOfRecord = Integer.valueOf(JOptionPane.showInputDialog("Record:"));
if (numberOfRecord < 0) {
throw new NegativeValueException("NegativeValue");
}
break;

} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error number format");

} catch (HeadlessException e) {

e.printStackTrace();
} catch (NegativeValueException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
return numberOfRecord;
}

@Override
public Student[] goToArmy() {

int n = 0;
for (int i = 0; i < group.length; i++) {
if (group[i] == null) {
i++;
} else if (group[i].getAge() >= 18 && group[i].isSex()) {
n += 1;
}

}
Student[] st = new Student[n];
int k = 0;
for (int i = 0; i < group.length; i++) {
if (group[i] == null) {
i++;
} else if (group[i].getAge() >= 18 && group[i].isSex()) {

st[k] = group[i];
k++;
}
}
return st;
}

@Override
public String toString() {
return "Group [getGroup()=" + totalGroup() + "]";
}

}


Class SerializeGroup
package com.gmail.ua.dmazur;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializeGroup implements Serializable {

private static final long serialVersionUID = 1L;

public static void saveGroup(Serializable obj, File file) throws IOException {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
oos.writeObject(obj);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
throw e;
}
}

public static Serializable loadGroupFromFile(File file) throws IOException, ClassNotFoundException {
try (ObjectInput oi = new ObjectInputStream(new FileInputStream(file))) {
return (Serializable) oi.readObject();
} catch (IOException e) {
throw e;
}
}

}


Class Main
package com.gmail.ua.dmazur;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

public class Main {

public static void main(String[] args) {
Student student1 = new Student("Ivanov1", "Ivan1", 17, true, 10, 12);
Student student2 = new Student("Petrov2", "Ivan2", 18, true, 11, 12);
Student student3 = new Student("Ivanov3", "Ivan3", 19, false, 12, 12);
Student student4 = new Student("Petrov4", "Ivan4", 17, true, 13, 12);
Student student5 = new Student("Ivanov5", "Ivan5", 18, true, 14, 12);
Student student6 = new Student("Petrov6", "Ivan6", 19, false, 15, 13);
Student student7 = new Student("Ivanov7", "Ivan7", 17, true, 16, 12);
Student student8 = new Student("Petrov8", "Ivan8", 18, true, 17, 12);
Student student9 = new Student("Ivanov9", "Ivan9", 19, false, 18, 12);
Student student10 = new Student("Petrov10", "Ivan10", 17, true, 19, 12);
Student student11 = new Student("Ivanov11", "Ivan11", 18, true, 20, 12);
Student student12 = new Student("Petrov12", "Ivan12", 18, true, 21, 12);
Group group = new Group();

group.addStudent(student1);
group.addStudent(student2);
group.addStudent(student3);
group.addStudent(student4);
group.addStudent(student5);
group.addStudent(student6);
group.addStudent(student7);
group.addStudent(student8);
group.addStudent(student9);
group.addStudent(student10);
group.addStudent(student11);
group.addStudent(student12);

System.out.println(group);
//System.out.println();
//group.delStudent(19);
//System.out.println();

//group.addNewStudent();
//System.out.println(group);
//System.out.println();

//group.addNewStudent();
// group.delStudent(45);
// System.out.println(group);
// group.addStudent(student12);
// System.out.println(group);
//System.out.println(group.findStudent("ivanov9"));
//System.out.println(group.findStudent("ivanov99"));
//System.out.println();
// group.arraysSortSurname();
//System.out.println(Arrays.toString(group.goToArmy()));

File f = new File ("GroupDataBase.txt");
try {
SerializeGroup.saveGroup(group, f);
} catch (IOException e) {
e.printStackTrace();
}

Group group2 = new Group(null);
try {
group2 = (Group) SerializeGroup.loadGroupFromFile(f);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println();
System.out.println(group2);
}

}


Alexander Ts

  • Преподаватели
  • Пользователи
  • *
  • Сообщений: 13980
    • Просмотр профиля
    • E-mail
Re: Java OOP Alexander 07.07.2020 (Жилянская Вт-Чт)
« Ответ #54 : Августа 02, 2020, 10:33:53 pm »
DenisMazur

Решение верное

OlhaKrynytska

  • Пользователи
  • *
  • Сообщений: 20
    • Просмотр профиля
    • E-mail
Re: Java OOP Alexander 07.07.2020 (Жилянская Вт-Чт)
« Ответ #55 : Августа 03, 2020, 12:31:00 am »
Используя стандартный методы сериализации создайте мини-базу данных для работы с группами студентов (возможность записи и чтения базы из файла по запросу пользователя).
package com.gmail.koa;

import java.io.Serializable;

public class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String surname;
private int studentNumber;
private double averageSc;

public Student(String name, String surname, int studentNumber, double averageSc) {
super();
this.name = name;
this.surname = surname;
this.studentNumber = studentNumber;
this.averageSc = averageSc;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getSurname() {
return surname;
}

public void setSurname(String surname) {
this.surname = surname;
}

public int getStudentNumber() {
return studentNumber;
}

public void setStudentNumber(int studentNumber) {
this.studentNumber = studentNumber;
}

public double getAverageSc() {
return averageSc;
}

public void setAverageSc(double averageSc) {
this.averageSc = averageSc;
}

@Override
public String toString() {
return "Student [name=" + name + ", surname=" + surname + ", studentNumber=" + studentNumber + ", averageSc="
+ averageSc + "]";
}

}


package com.gmail.koa;

import java.io.Serializable;
import java.util.Arrays;

public class Group implements Serializable {

private Student[] group = new Student[5];
private int numberGroup;
private static final long serialVersionUID = 1L;

public Group(Student[] group, int numberGroup) {
super();
this.group = group;
this.numberGroup = numberGroup;
}

public Student[] getGroup() {
return group;
}

public void setGroup(Student[] group) {
this.group = group;
}

public int getNumberGroup() {
return numberGroup;
}

public void setNumberGroup(int numberGroup) {
this.numberGroup = numberGroup;
}

@Override
public String toString() {
return "Group [group=" + Arrays.toString(group) + ", numberGroup=" + numberGroup + "]";
}

}


package com.gmail.koa;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Main {

public static void main(String[] args) {
Student s1 = new Student("Masha", "Ivanova", 222, 2.34);
Student s2 = new Student("Misha", "Petrov", 333, 5.32);
Student s3 = new Student("Lena", "Vetrova", 444, 3.21);
Student s4 = new Student("Kirill", "Sidorov", 555, 8.54);
Student s5 = new Student("Marina", "Bulkina", 666, 7.69);
Student s6 = new Student("Petia", "Orechov", 777, 4.87);
Student s7 = new Student("Katia", "Smirnova", 888, 9.34);
Student s8 = new Student("Oleh", "Kurochkin", 999, 2.47);
Student s9 = new Student("Ania", "Belaia", 111, 7.52);
Student s10 = new Student("Vitia", "Durnev", 000, 6.29);
Student s11 = new Student("Olia", "Poliakova", 666, 7.69);
Student s12 = new Student("Oleh", "Vinnic", 777, 4.87);
Student s13 = new Student("Maks", "Barskih", 888, 9.34);
Student s14 = new Student("Vera", "Brejneva", 999, 2.47);
Student s15 = new Student("Filip", "Kirkoriv", 111, 7.52);

Student[] arr1 = new Student[] { s1, s2, s3, s4, s5 };
Student[] arr2 = new Student[] { s6, s7, s8, s9, s10 };
Student[] arr3 = new Student[] { s11, s12, s13, s14, s15 };
Group g1 = new Group(arr1, 345);
Group g2 = new Group(arr2, 346);
Group g3 = new Group(arr3, 347);

try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("fil"))) {
oos.writeObject(g1);
oos.writeObject(g2);
oos.writeObject(g3);
} catch (IOException e) {
System.out.println("don't save group");

}
Group g4 = null;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("fil"))) {
g4 = (Group) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
System.out.println("not read");
}
System.out.println(g4);
}

}


Alexander Ts

  • Преподаватели
  • Пользователи
  • *
  • Сообщений: 13980
    • Просмотр профиля
    • E-mail
Re: Java OOP Alexander 07.07.2020 (Жилянская Вт-Чт)
« Ответ #56 : Августа 04, 2020, 12:01:25 am »

OlhaKrynytska

Решение верное

YuraKhomenko

  • Пользователи
  • *
  • Сообщений: 49
    • Просмотр профиля
Re: Java OOP Alexander 07.07.2020 (Жилянская Вт-Чт)
« Ответ #57 : Августа 04, 2020, 12:49:40 am »
Используя стандартный методы сериализации создайте мини-базу данных для работы с группами студентов (возможность записи и чтения базы из файла по запросу пользователя).


package com.gmail.yurakhomenko2018;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;

public class Main {

public static void main(String[] args) {
// TODO Auto-generated method stub

Group group = new Group();

group.addHuman("Alexander", "Aleksandrov", 18);
group.addHuman("Alexey", "Alekseev", 19);
group.addHuman("Katia", "Potapova", 18);
group.addHuman("Alexander1", "Aleksandrov1", 17);
group.addHuman("Alexey", "Alekseev", 19);
group.addHuman("Katia1", "Potapova1", 17);
group.addHuman("Alexander2", "Aleksandrov2", 23);
group.addHuman("Alexey2", "Alekseev2", 20);
group.addHuman("Katia2", "Potapova2", 21);
System.out.println();
group.printgroup();
System.out.println();

try (ObjectOutputStream OOS = new ObjectOutputStream(new FileOutputStream("fileGroup.csv"))) {
OOS.writeObject(group);
} catch (IOException e) {
System.out.println("Group no save");
}
Group anotherGroup = null;
try (ObjectInputStream OIS = new ObjectInputStream(new FileInputStream("fileGroup.csv"))) {
anotherGroup = (Group) OIS.readObject();
} catch (IOException | ClassNotFoundException e) {
System.out.println("Group not load");
}
System.out.println();
anotherGroup.printgroup();
}

}



YuraKhomenko

  • Пользователи
  • *
  • Сообщений: 49
    • Просмотр профиля
Re: Java OOP Alexander 07.07.2020 (Жилянская Вт-Чт)
« Ответ #58 : Августа 04, 2020, 12:50:17 am »
Group


package com.gmail.yurakhomenko2018;

import java.io.Serializable;

public class Group implements Serializable {
private Human[] group;
private static final long serialVersionUID = 1L;

Group() {
group = new Human[0];
}

public void addHuman(String name, String lastName, int age) {
Human[] h = new Human[group.length + 1];
System.arraycopy(group, 0, h, 0, group.length);
h[h.length - 1] = new Human(name, lastName, age);
group = h;
}

public void printgroup() {
for (Human human : group) {
System.out.println(human);
}
}
}



YuraKhomenko

  • Пользователи
  • *
  • Сообщений: 49
    • Просмотр профиля
Re: Java OOP Alexander 07.07.2020 (Жилянская Вт-Чт)
« Ответ #59 : Августа 04, 2020, 12:51:02 am »
Human


package com.gmail.yurakhomenko2018;

import java.io.Serializable;

public class Human implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String lastName;
private int age;


public Human(String name, String lastName, int age) {
super();
this.name = name;
this.lastName = lastName;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

@Override
public String toString() {
return "Human [name=" + name + ", lastName=" + lastName + ", age=" + age + "]";
}

}