0

В общем в файле записаны объект Person у которого имеется Имя(name) , Фамилия(Surname), Отчество(Secondname) и дата рождения(age). Нужно по фамилии найти человека в этом списке и вывести на консоль. Также нужно отсортировать по фамилиям( A - Z )

Пример index.txt:

Ivan Ivanov Ivanovich 01.01.1999
Petr Petrov Petrovich 02.02.2000
...

Объект Person:

public class Person implements Serializable {
    private static int countId = 0;
    public String Name;
    public String Surname;
    public String SecondName;
    public String age;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age.equals(person.age) &&
                Objects.equals(Name, person.Name) &&
                Surname.equals(person.Surname) && SecondName.equals(person.SecondName);
    }
    public Person(String Name,String Surname,String SecondName,String age){
        this.Name = Name;
        this.Surname = Surname;
        this.SecondName = SecondName;
        this.age = age;
    }

    public void SetName(String Name){
        this.Name = Name;
    }
    public void SetSurname(String Surname){
        this.Surname = Surname;
    }
    public void SetSecondName(String SecondName){
        this.SecondName = SecondName;
    }
    public void SetAge(String age) {
        this.age = age;
    }

    public String GetName(){
        return this.Name;
    }
    public String GetSurname(){
        return this.Surname;
    }
    public String GetSecondName(){
        return this.SecondName;
    }
    public String GetAge(){
        return this.age;
    }

    void show_all() {
        System.out.println("Пользователь: "); //USER
        System.out.println("Имя: " + GetName()); //NAME
        System.out.println("Фамилия: " + GetSurname()); //SURNAME
        System.out.println("Отчество: " + GetSecondName()); //SECONDNAME
        System.out.println("Дата Рождения: " + GetAge()); //DATE
    }

    public String toString() {
        return "\n " + Name +
                "\n " + Surname +
                 "\n " + SecondName +
                  "\n " + age + "\n";
    }
}

Код вывода данных из файла:

public static void showAll() throws IOException {

        String list;
        Scanner put = new Scanner(System.in);
        System.out.print("Из какого файла загрузить: ");
        list = put.nextLine();

        System.out.println("");

        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(list + ".txt"), StandardCharsets.UTF_8));
        String str;
        while ((str = in.readLine()) != null) {
            System.out.println(str);
        }
        in.close();
    }

Попытка сделать поиск по фамилии(но не особо удачно):

public static void search() throws IOException {
        System.out.println();
        String list;
        Scanner in = new Scanner(System.in);
        System.out.print("Ввод: ");
        list = in.nextLine();
        ArrayList<Person> saveAllLinesForRewriting = new ArrayList<>();

        if (saveAllLinesForRewriting.toString().contains(list)) {
            System.out.println("Found: " + list);
        } else {
            System.out.println("No data found.");
        }
    }
1
  • ??? поиск по фамилии и сортировка по ней же?
    – Miron
    19 янв 2020 в 8:33

3 ответа 3

0

Сделал настраиваемый поиск(не только по фамилии, и сортировка тоже настраивается). Вот метод:

public <T>boolean searchBy(Comparator<Person> comp, Function<Person, T> getControlPerson, Function<String, T> getControlConsole, String controlName) {
    if(dataBase == null) {
        throw new IllegalStateException();
    }
    Scanner in = new Scanner(System.in);
    System.out.print("Запишите " + controlName + ", по которому(ой) будет производиться поиск: ");
    T control = getControlConsole.apply(in.nextLine());
    ArrayList<Person> found = new ArrayList<Person>();
    dataBase.forEach(a -> {
        if(getControlPerson.apply(a).equals(control)){
            found.add(a);
        }
    });
    if(found.isEmpty()) {
        System.out.println("В базе данных нет записей, удовлетворяющих условию");
        return false;
    } else {
        System.out.println("Поиск дал следующие результаты: ");
        found.sort(comp);
        found.forEach(System.out::println);
        return true;
    }
}

Этот метод находится в классе PersonDatabase:

class PersonDatabase{
    private ArrayList<Person> dataBase;

    public boolean showDatabase() {
        if(dataBase == null) {
            return false;
        }
        dataBase.forEach(System.out::println);
        return true;
    }

    //здесь searchBy();

    @SuppressWarnings("resource")
    public boolean getDatabaseFromFile() throws FileNotFoundException {
        File inFile;
        Scanner fileScanner;
        Scanner put = new Scanner(System.in);
        System.out.print("Из какого файла загрузить: ");
        try{
            inFile = new File(put.nextLine());
            System.out.println();
        } catch(NullPointerException n) {
            System.err.println("Такого файла не существует");
            return false;
        }

        dataBase = new ArrayList<Person>(100);
        fileScanner = new Scanner(new FileInputStream(inFile));
        int lineNumber = 1;
        try {
            while(fileScanner.hasNextLine()) {
                dataBase.add(Person.parse(fileScanner.nextLine()));
                lineNumber++;
            }
        } catch(IllegalArgumentException e) {
            System.err.println(e.getMessage() + " Строка " + lineNumber + " не отвечает стандартам");
        }
        return true;
    }
}

Класс Person(оставил только добавленное, чтобы было понятно):

class Person implements Serializable {
    //...

    public static Person parse(String string) {
        String[] parts = string.split(" ");
        if(parts.length != 4) {
            throw new IllegalArgumentException("Всего элементов в строке должно быть 4!");
        }
        if(!isDate(parts[3])) {
            throw new IllegalArgumentException("Дата записана неверно!");
        }
        return new Person(parts[0], parts[1], parts[2], parts[3]);
    }

    private static boolean isDate(String date) {
        return date.length() == 2 + 1 + 2 + 1 + 4 && 
                    isNumber(date.substring(0, 2)) && 
                    date.charAt(2) == '.' &&
                    isNumber(date.substring(3, 5)) &&
                    date.charAt(5) == '.' &&
                    isNumber(date.substring(6, 10));

    }

    private static boolean isNumber(String string) {
        for(char ch : string.toCharArray()) {
            if(!isNumber(ch)) {
                return false;
            }
        }
        return true;
    }

    private static boolean isNumber(char ch) {
        return ch == '0' || ch == '1' || ch == '2' || ch == '3' || ch == '4' ||
                    ch == '5' || ch == '6' || ch == '7' || ch == '8' || ch == '9'; 
    }

    public int compareBySurname(Person p) {
        return Surname.compareTo(p.Surname);
    }

    public int compareByDate(Person p) {
        int myYear = Integer.parseInt(age.substring(6, 10));
        int pYear = Integer.parseInt(p.age.substring(6, 10));
        int myMonth = Integer.parseInt(age.substring(3, 5));
        int pMonth = Integer.parseInt(age.substring(3, 5));
        int myDay = Integer.parseInt(age.substring(0, 2));
        int pDay = Integer.parseInt(age.substring(0, 2));
        if(myYear > pYear) {
            return -1;
        } else if(myYear == pYear) {
            if(myMonth > pMonth) {
                return -1;
            } else if(myMonth == pMonth) {
                return pDay - myDay;
            } else {
                return 1;
            }
        } else {
            return 1;
        }
    }
    //...
}

Замечу, что вы забыли поля сделать private - иначе зачем вы get-еры и set-еры делали.
Переходим к тестам этого дела.
Метод main(поиск по фамилии, сортировка по дате):

PersonDatabase database = new PersonDatabase();
database.getDatabaseFromFile();
database.<String>searchBy(Person::compareByDate,
                                              (Person a) -> a.Surname,
                                              (String a) -> a,
                                              "фамилию");

Содержимое файла(Persons.txt), используемого при тесте:

a c c 12.12.2019
a b c 03.03.2012
a c c 12.12.2012
a r c 02.03.2012

Сам тест(консоль):

Из какого файла загрузить: Persons.txt

Запишите фамилию, по которому(ой) будет производиться поиск: c
Поиск дал следующие результаты:

a c c
12.12.2019

a c c
12.12.2012

Метод putPersonsInFileWithConsole из класса PersonDatabase:

public static boolean putPersonsInFileWithConsole() throws IOException {
    PrintWriter printWriter;
    File inFile;
    Scanner put = new Scanner(System.in);
    System.out.print("В какой файл добавлять: ");
    try{
        inFile = new File(put.nextLine());
        System.out.println();
    } catch(NullPointerException n) {
        System.err.println("Такого файла не существует");
        return false;
    }

    BufferedWriter bufferWriter = new BufferedWriter(new FileWriter(inFile, true));
    String inLine = null;
    System.out.println("Чтобы выйти - напечатайте слово 'выйти'");
     do {
        System.out.println("Введите информацию о человеке в следующем формате: 'имя фамилия отчество дата_рождения(**.**.****):'");
        inLine = put.nextLine();
        if(inLine.equals("выйти")) {
            break;
        }
        String[] parts = inLine.split(" ");
        if(parts.length != 4) {
            System.err.println("Всего элементов в строке должно быть 4!");
            continue;
        }
        if(!Person.isDate(parts[3])) {
            System.err.println("Дата записана неверно!");
            continue;
        }
        bufferWriter.newLine();
        bufferWriter.write(inLine);
        bufferWriter.flush();
    } while(true);
     bufferWriter.close();
     return true;
}
13
  • if(dataBase == null) { throw new IllegalStateException(); } и dataBase.forEach(a -> { if(getControlPerson.apply(a).equals(control)){ found.add(a); } Какой database используете? у меня красным они выделены
    – Neisuz
    19 янв 2020 в 9:27
  • И если мне необходимо добавить Person в этот файл через консоль, как тогда поступить?
    – Neisuz
    19 янв 2020 в 9:29
  • @Neisuz этот метод находится в классе PersonDatabase. Я даже комментарий оставил, мол, здесь вставляется этот метод
    – Miron
    19 янв 2020 в 9:49
  • @Neisuz в таком случае нужно написать соответствующий метод: допустим, putPersonsWithConsole()
    – Miron
    19 янв 2020 в 9:50
  • *putPersonsInFileWithConsole
    – Miron
    19 янв 2020 в 9:58
0
public static class SurnameComparator implements 
Comparator<Person> {
        public int compare(Person h1, Person h2) {
            if (h1.surname.equals(h2.surname)) {
                return 1;
            }
            else {
                return -1;
            }
        }
    }   Так нужно сравнивать?  

Как должен выглядеть метод getAll?

public void getAll(String Name,String Surname,String SecondName,String age){
        TreeSet<Person> myPersonArrayList = new TreeSet<>();
        System.out.println(GetName() + "" + GetSecondName() + "" + GetSurname() + "" + GetAge());
//        ???
    }
0

Про объект Person - все имена методов называйте с маленькой буквы. В классе Person имплементируйте интерфейс Comparable - реализуйте метод compareTo() Вместо showAll сделайте метод getAll() - он должен возвращать TreeSet - коллекцию всех людей из файла. В метод search передавайте коллекцию людей и ту фамилию которую хотите найте и делаете цикл по коллекции.

Например так

public class Person implements Comparable<Person>{
private static int countId = 0;
private String name;
private String surname;
private String secondName;
private String age;

public Person(String name,String surname,String secondName,String age){
    this.name       = name;
    this.surname    = surname;
    this.secondName = secondName;
    this.age        = age;
}


public String getName(){

    return Name;
}


public void setName( String name ){

    Name = name;
}


public String getSurname(){

    return Surname;
}


public void setSurname( String surname ){

    Surname = surname;
}


public String getSecondName(){

    return SecondName;
}


public void setSecondName( String secondName ){

    SecondName = secondName;
}


public String getAge(){

    return age;
}


public void setAge( String age ){

    this.age = age;
}


public int compareTo( Person o ){
    if (this.equals( o )){
        return 0;
    }
    return this.getName().compareTo( o.getName() );
}


@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Person person = (Person) o;
    return age.equals(person.age) &&
           Objects.equals( name, person.name ) &&
           surname.equals( person.surname ) && secondName.equals( person.secondName );
}
}

И сервис

 public class PersonService{

public static Set<Person> getAll( String filePath ){
    Set<Person> res = new TreeSet<>();
    try(FileInputStream fis =  new FileInputStream( filePath);
        InputStreamReader isr = new InputStreamReader( fis, StandardCharsets.UTF_8);
        BufferedReader reader = new BufferedReader(isr)){

        String strInfo;
        while( (strInfo = reader.readLine()) != null){
            String[] arrInfo = strInfo.split( " " );
            res.add( new Person(arrInfo[0],arrInfo[1],arrInfo[2],arrInfo[3]) );
        }

    }catch( IOException e){
        e.printStackTrace();
    }
    return res;
}


public static Set<Person> search(Set<Person> persons, String surname){
    Set<Person> res = new TreeSet<>();
    for( Person person : persons){
        if(person.getSurname().equals( surname )){
            res.add(person);
        }
    }
    return res;
}

public static void main(String[]args){
    Scanner put = new Scanner( System.in);

    System.out.print("Из какого файла загрузить: ");
    String filePath = put.nextLine();
    Set<Person> allPersons = getAll(filePath);

    System.out.println("Введите фамилию: ");
    String surname = put.nextLine();
    Set<Person> searchResult = search(allPersons, surname);

    for( Person person: searchResult ){
        System.out.println(person);
    }

    put.close();
}

}
3
  • А если мне необходимо добавить новый Person в файл ? Нужно создавать метод в нем создавать лист с объектом Person и вызывать set.name и т.д. ?
    – Neisuz
    19 янв 2020 в 8:09
  • я добавил пример в ответ
    – Z.John
    19 янв 2020 в 9:07
  • Огромное спасибо
    – Neisuz
    19 янв 2020 в 11:56

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.