• Июня 16, 2019, 05:40:12 am
• Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Не получили письмо с кодом активации?
Новости: Вебинар о выборе IT профессии и руководство для новичков: http://bit.ly/2HG2vFp

Автор Тема: Java_OOP_Alexander_Beresteyka_29_05_2019  (Прочитано 371 раз)

TIgor

  • Пользователи
  • *
  • Сообщений: 20
    • Просмотр профиля
Re: Java_OOP_Alexander_Beresteyka_29_05_2019
« Ответ #45 : Июня 11, 2019, 03:34:48 pm »
---

Alexander Ts

  • Преподаватели
  • Пользователи
  • *
  • Сообщений: 11812
    • Просмотр профиля
    • E-mail
Re: Java_OOP_Alexander_Beresteyka_29_05_2019
« Ответ #46 : Июня 12, 2019, 01:46:16 pm »

TIgor

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

TIgor

  • Пользователи
  • *
  • Сообщений: 20
    • Просмотр профиля
Re: Java_OOP_Alexander_Beresteyka_29_05_2019
« Ответ #47 : Июня 14, 2019, 02:54:53 pm »
ДЗ 4
Задание 1-2
Класс StreamService
package net.ukr.tigor.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

public class StreamService {

public static void streamCopy(InputStream is, OutputStream os) throws IOException {

if (is == null || os == null) {
throw new IllegalArgumentException("Null stream pointer");
}
int readByte = 0;
byte[] buffer = new byte[1024 * 1024];

for (; (readByte = is.read(buffer)) > 0;) {
os.write(buffer, 0, readByte);
}

}

public static void fileCopy(File original, File copy) throws IOException {
try (InputStream is = new FileInputStream(original); OutputStream os = new FileOutputStream(copy)) {
streamCopy(is, os);
} catch (IOException e) {
throw e;
}
}

public static void DirCopy(File from, File to, FileFilter ff) throws IOException {
File copyFile;
File[] arrFiles = from.listFiles(ff);
for (File file : arrFiles) {
copyFile = new File(to.getPath() + "\\" + file.getName());
try {
fileCopy(file, copyFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static String getStringDifferentWords(File[] arrFiles, String [][] arrString ) {

String result = "";

int maxLength = 0;
for (int i = 0; i < arrFiles.length; i++) {
arrString[i] = fillArray(arrFiles[i]);
if (maxLength < arrString[i].length) {
maxLength = arrString[i].length;
}
for (String str : arrString[i]) {
if (!result.contains(str)) {
result += str + " ";
}
}
}

return result;
}

public static String[] getResultArray(File[] arrFiles) {

String[][] arrString = new String[arrFiles.length][];

//формируем массивы слов из файлов и получаем строку со словами без повторений
String differentWords = getStringDifferentWords(arrFiles,arrString);

String[] arrDifWord = differentWords.split("[ ]");

// проверяем наличие слова в каждой строке<-массиве<-файле
for (int k = 0; k < arrDifWord.length; k++) {
int count = 0;
for (int i = 0; i < arrString.length; i++) {

for (int j = 0; j < arrString[i].length; j++) {
if (arrDifWord[k].equalsIgnoreCase(arrString[i][j])) {
++count;
break;
}
}
}
if (count != arrString.length) {
arrDifWord[k] = "";

}
}

return arrDifWord;

}

public static File assemblyFiles(File... arrFiles) throws IOException {

File result = new File("result.txt");

String[] arrDifWord = getResultArray(arrFiles);

try (PrintWriter pw = new PrintWriter(result)) {
for (String str : arrDifWord) {
if (str == "") {
continue;
}
pw.println(str);
}
} catch (FileNotFoundException e) {
System.out.println("Error file writer");
}

return result;
}

private static String[] fillArray(File file) {

StringBuffer sb = new StringBuffer();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String text = "";
for (; (text = br.readLine()) != null;) {
sb.append(text);
}
} catch (IOException e) {
System.out.println(e);
}
String[] arr = sb.toString().split("[ ]");
for (String string : arr) {
string = string.toLowerCase();
}
return arr;
}
}


Класс UserFileFilter
package net.ukr.tigor.service;

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

public class UserFileFilter implements FileFilter {

private String[] arr;

public UserFileFilter(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);
}

}


Класс Main
package net.ukr.tigor;

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

import net.ukr.tigor.service.*;

public class Main {

public static void main(String[] args) {


File folderFrom = new File("folder_from");
showContentDir(folderFrom,null,"All files & catalogs in folder-source:");

UserFileFilter ff = new UserFileFilter("txt", "doc");

showContentDir(folderFrom,ff,"Files after using the filter:");

File folderTo = new File("folder_to");

try {
StreamService.DirCopy(folderFrom, folderTo, ff);
} catch (IOException e) {
e.printStackTrace();
}
showContentDir(folderTo,null,"All files & catalogs in folder receiver");

try {
// выбираем произвольное к-во txt-файлов для анализа
File assemblyFil = StreamService.assemblyFiles(folderFrom.listFiles(new UserFileFilter("txt")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


public static void showContentDir(File dir, UserFileFilter ff, String message) {

System.out.println(message);
File[] arrFiles = dir.listFiles(ff);
for (File file : arrFiles) {
System.out.println(file.getPath());
}

System.out.println();
}


}


Задание 3-4
Класс Human
package net.ukr.tigor;

import net.ukr.tigor.service.Sex;

public class Human {

private int age;
private Sex sex;
private String fullName;
private int height;
private int weight;

public Human(int age, Sex sex, String fullName,int height, int weight) {
super();
this.age = age;
this.sex = sex;
this.fullName = fullName;
this.height = height;
this.weight = weight;
}

public Human() {
super();
}

public int getAge() {
return age;
}

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

public Sex getSex() {
return sex;
}

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

public int getHeight() {
return height;
}

public void setHeight(int height) {
this.height = height;
}

public int getWeight() {
return weight;
}

public String getFullName() {
return fullName;
}

public void setFullName(String fullName) {
this.fullName = fullName;
}

public void setWeight(int weight) {
this.weight = weight;
}

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





}


Класс Student
package net.ukr.tigor;

import net.ukr.tigor.service.Sex;

public class Student extends Human{

private int numberOfRecBook;

public Student() {
super();
}

public Student(int age, Sex sex, String fullName, int height, int weight, int numberOfRecBook) {
super(age, sex, fullName, height, weight);
this.numberOfRecBook = numberOfRecBook;
}

public Student(String [] arrFields) {
super(Integer.parseInt(arrFields[1]),Sex.fromString(arrFields[2]),arrFields[0],Integer.parseInt(arrFields[3]),Integer.parseInt(arrFields[4]));

this.numberOfRecBook = Integer.parseInt(arrFields[5]);
}

public int getNumberOfRecBook() {
return numberOfRecBook;
}

public void setNumberOfRecBook(int numberOfRecBook) {
this.numberOfRecBook = numberOfRecBook;
}

@Override
public String toString() {
return getFullName() +";" +getAge()+";" + getSex().getValue() + ";" +getHeight()+ ";"+getWeight()+ ";" +getNumberOfRecBook();
}

}

Класс Group
package net.ukr.tigor;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

import javax.swing.JOptionPane;

import net.ukr.tigor.service.FieldsForCompare;
import net.ukr.tigor.service.FullGroupException;
import net.ukr.tigor.service.Sex;
import net.ukr.tigor.service.StudentComparator;

public class Group implements RecruitmentOffice {

private String name;
private Student[] arrGroup = new Student[10];

public Group() {
super();
}

public Group(String name) {
super();
this.name = name;
}

public String getName() {
return name;
}

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

public void addStudentInteractive() {

try {

String str = JOptionPane.showInputDialog(
"Input description of student <name;age;m(ale)/f(emale);height;weight;number of rec.book>");

String[] arrFields = str.split(";");
if (arrFields.length == 6) {

Student newStudent = new Student();
newStudent.setFullName(arrFields[0]);
newStudent.setAge(Integer.parseInt(arrFields[1]));
newStudent.setSex((arrFields[2] == "m") ? Sex.MALE : Sex.FEMALE);
newStudent.setHeight(Integer.parseInt(arrFields[3]));
newStudent.setWeight(Integer.parseInt(arrFields[4]));
newStudent.setNumberOfRecBook(Integer.parseInt(arrFields[5]));

try {
addStudent(newStudent);
} catch (FullGroupException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}

} else {
System.out.println("Incorrect input description of student");
}

addStudentInteractive();
} catch (NullPointerException e) {

}

}

public void addStudent(Student student) throws FullGroupException {

int lastIndex = getLastIndex();

if (lastIndex < 0) {
throw new FullGroupException();
}

if (findStudentByName(student.getFullName()) == null) {
arrGroup[lastIndex] = student;
System.out.println("Student " + student + " is add to group " + getName());
} else {
System.out.println("Student " + student + " is not add to group " + getName()
+ ". Student is already a member of this group");
}

}

public void dellStudent(Student studentFoDel) {

boolean ok = false;
for (int i = 0; i < arrGroup.length; i++) {

if (arrGroup[i] == null) {
continue;
}

if (arrGroup[i].getFullName().equals(studentFoDel.getFullName())) {
arrGroup[i] = null;
ok = true;
}
}

if (ok) {
System.out.println("Student " + studentFoDel + " is delete from group " + getName());
} else {
System.out.println("Student " + studentFoDel + " is not delete from group " + getName()
+ ". Student is not a member of this group");

}

}

public int getLastIndex() {

int result = -1;

for (int i = 0; i < arrGroup.length; i++) {
if (arrGroup[i] == null) {
result = i;
break;
}
}
return result;
}

public Student findStudentByName(String fullname) {

Student result = null;

for (Student student : arrGroup) {
if (student == null) {
continue;
}
if (student.getFullName().equalsIgnoreCase(fullname)) {
result = student;
break;
}
}

return result;
}

public void sortStud(boolean revers, FieldsForCompare param) {

Arrays.sort(arrGroup, new StudentComparator(revers, param));

}

public void saveGroup(File file) throws IOException {

try (PrintWriter pw = new PrintWriter(file)) {

StringBuilder sb = new StringBuilder();

sb.append("[").append(getName()).append(System.lineSeparator());

for (Student student : arrGroup) {
sb.append(student).append(System.lineSeparator());
}

sb.append("]").append(System.lineSeparator());

pw.write(sb.toString());

System.out.println("Group " + getName() + " saved successfully ");

} catch (IOException e) {
// TODO: handle exception
}

}

public void loadGroup(File file) throws IOException {

try (BufferedReader bf = new BufferedReader(new FileReader(file))) {
String str = "";
for (; (str = bf.readLine()) != null;) {

if (str.charAt(0) == '[') {
setName(str.substring(1));
}

if (str.charAt(0) == ']') {
break;
}

String[] arrFields = str.split(";");
if (arrFields.length == 6) {

Student newStudent = new Student(arrFields);
System.out.println(newStudent);
try {
addStudent(newStudent);
} catch (FullGroupException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
}
}

}
}

@Override
public Student[] getReservists() {

Student[] arrReservists = new Student[arrGroup.length];
int n = 0;
for (Student student : arrGroup) {

if (student != null && student.getAge() > 18 && student.getSex() == Sex.MALE) {
arrReservists[n] = student;
n += 1;
}
}

arrReservists = Arrays.copyOf(arrReservists, n);

return arrReservists;
}

@Override
public String toString() {

String result = " members: \n";
for (int i = 0; i < arrGroup.length; i++) {

if (arrGroup[i] == null) {
break;
}

result += (i + 1) + ": " + arrGroup[i].getFullName() + ", age: " + arrGroup[i].getAge() + ", sex: " + arrGroup[i].getSex()
+ " num. of rec. book: " + arrGroup[i].getNumberOfRecBook() + "\n";
}

return "Group: " + name + result + "";
}

}


Сервисные классы:
1. Sex
package net.ukr.tigor.service;

public enum Sex {
MALE("Male"), FEMALE("Female");

private String value;

private Sex(String value) {
this.value = value;
}

public String getValue() {
return value;
}

public static Sex fromString(String value) {
if (value != null) {
for (Sex sex : Sex.values()) {
if (value.equalsIgnoreCase(sex.value)) {
return sex;
}
}
}
throw new IllegalArgumentException("No such value");
}

}

2. StudentComparator
package net.ukr.tigor.service;

import java.util.Comparator;

import net.ukr.tigor.Student;

public class StudentComparator implements Comparator {

private boolean revers;
private FieldsForCompare param;

public StudentComparator(boolean revers, FieldsForCompare param) {
super();
this.revers = revers;
this.param = param;
}

public StudentComparator() {
super();
}

public int compare(Object o1, Object o2) {

int result = NullComparator.checkNull(o1, o2);
if (result == 7) {

Student a = (Student) o1;
Student b = (Student) o2;
switch (param) {
case NAME:
result = a.getFullName().compareToIgnoreCase(b.getFullName());
break;
case AGE:
if (a.getAge() > b.getAge()) {
result = 1;
}
if (a.getAge() < b.getAge()) {
result = -1;
}
if (a.getAge() == b.getAge()) {
result = 0;
}
break;
case NRB:
if (a.getNumberOfRecBook() > b.getNumberOfRecBook()) {
result = 1;
}
if (a.getNumberOfRecBook() < b.getNumberOfRecBook()) {
result = -1;
}
if (a.getNumberOfRecBook() == b.getNumberOfRecBook()) {
result = 0;
}
break;
default:
result = a.getFullName().compareToIgnoreCase(b.getFullName());
}
}
if (this.revers){
result *= -1;
}

return result;
}

}

3. FullGroupException
package net.ukr.tigor.service;

public class FullGroupException extends Exception{

@Override
public String toString() {
return "Add student exception: group is full";
}

@Override
public String getMessage() {
// TODO Auto-generated method stub
return "Add student exception: group is full";
}

}


4. NullComparator
package net.ukr.tigor.service;

public class NullComparator {

public static final int NOT_NULL = 7;
 
  public static int checkNull(Object a, Object b) {
    if (a != null && b == null) {
      return 1;
    }
    if (a == null && b != null) {
      return -1;
    }
    if (a == null && b == null) {
      return 0;
    }
    return 7;
  }
}

5. FieldsForCompare
package net.ukr.tigor.service;

public enum FieldsForCompare{
NAME,AGE,NRB;
}

Класс Main
package net.ukr.tigor;

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


import net.ukr.tigor.service.*;

public class Main {

public static void main(String[] args) {

Group gr126 = new Group("126");

Student stud1 = new Student(16, Sex.MALE, "Иванов Иван Иванович", 175, 60, 1111);
Student stud2 = new Student(17, Sex.MALE, "Петров Иван Иванович", 160, 60, 2222);
Student stud3 = new Student(18, Sex.MALE, "Сидоров Иван Иванович", 159, 50, 3333);
Student stud4 = new Student(19, Sex.MALE, "Свистунов Иван Иванович", 179, 70, 4444);
Student stud5 = new Student(19, Sex.MALE, "Сенча Иван Иванович", 195, 80, 5555);
Student stud6 = new Student(20, Sex.MALE, "Свиридов Иван Иванович", 200, 90, 6666);
Student stud7 = new Student(18, Sex.MALE, "Антончук Иван Иванович", 180, 80, 7777);
Student stud8 = new Student(17, Sex.MALE, "Музычко Иван Иванович", 198, 98, 8888);
Student stud9 = new Student(19, Sex.MALE, "Антонов Иван Иванович", 160, 80, 9999);
Student stud10 = new Student(19, Sex.FEMALE, "Леонова Юлия Ивановна", 160, 79, 0000);

addStud(gr126, stud1);
addStud(gr126, stud2);
addStud(gr126, stud3);
addStud(gr126, stud4);
addStud(gr126, stud5);
addStud(gr126, stud6);
addStud(gr126, stud7);
addStud(gr126, stud8);
addStud(gr126, stud9);
addStud(gr126, stud10);


File fg = new File("group.txt");
try {
gr126.saveGroup(fg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Group newGroup = new Group();
try {
newGroup.loadGroup(fg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println("Group from file: ");
System.out.println(newGroup);
}

public static void addStud(Group group, Student stud) {
try {
group.addStudent(stud);
} catch (FullGroupException e) {
System.out.println(e.getMessage());
}
}

}


serg87

  • Пользователи
  • *
  • Сообщений: 45
    • Просмотр профиля
    • E-mail
Re: Java_OOP_Alexander_Beresteyka_29_05_2019
« Ответ #48 : Июня 14, 2019, 06:00:33 pm »
Добрый день. Александр, вы можете сбросить на почту tsybulnikserg@gmail.com пример задачи, который мы решали по теме Полиморфизм и Исключения? Или может у кого то из ребят в группе остался пример.

Заранее благодарен.

Alexander Ts

  • Преподаватели
  • Пользователи
  • *
  • Сообщений: 11812
    • Просмотр профиля
    • E-mail
Re: Java_OOP_Alexander_Beresteyka_29_05_2019
« Ответ #49 : Июня 15, 2019, 10:42:28 pm »
TIgor

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