Как отредактировать этот метод для работы с массивом Customer? - PullRequest
2 голосов
/ 01 мая 2019

Я должен создать метод, который принимает идентификатор клиента, а затем возвращает индекс в массиве, если этот идентификатор найден.С помощью метода, принимающего только Integer ID.

Я использовал итеративный двоичный поиск, чтобы иметь возможность искать в моем списке массивов клиентов.Но проблема в том, что он застревает с типами операндов при сравнении массива Customer с целым числом.Я попытался изменить тип метода на static, CustomerList, Customer и т. Д. Но это никак не влияет на это.

cl в коде - это открытое поле, которое я создал в начале моего класса.

As -> public Customer [] cl;

**public class Person {
    private String firstName;
    private String lastName;
    private String address;
    private String city;
    private String state;
    private String zipCode;    

    public Person(String firstName, String lastName, String address, String city, String state, String zipCode) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.address = address;
        this.city = city;
        this.state = state;
        this.zipCode = zipCode;    
    }

    protected Person() {

    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return this.city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getZipCode() {
        return zipCode;
    }

    public void setZipCode(String zipCode) {
        this.zipCode = zipCode;
    }

    @Override
    public String toString() {
        return "FirstName: " + firstName + "\nLastName: " + lastName + "\nAddress: " + address + "\nCity: " + city + "\nState: " + state + "\nZipCode: " + zipCode;
    }

    public String toCSV() {
        return this.firstName + "," + this.lastName + "," + this.address + "," + this.city
                + "," + this.state + "," + this.zipCode;
    }

    public void copy(Person p) {       
        firstName = p.firstName;
        lastName = p.lastName;
        address = p.address;
        city = p.city;
        state = p.state;
        zipCode = p.zipCode;
    }

    public void copy(String firstName, String lastName, String address, String city, String state, String zipCode) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.address = address;
        this.city = city;
        this.zipCode = zipCode;
    }

    @Override
    public Person clone() {
        Person p = new Person(this.firstName, this.lastName, this.address, this.city, this.state, this.zipCode);
        return p;
    }
}**

**public class Customer extends Person{
    private int customerID;
    private double grossSales;

    public Customer(int customerID, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
        super(firstName, lastName, address, city, state, zipCode);
        this.customerID = customerID;
        this.grossSales = grossSales;
    }

    public Customer(String s, int customerID, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
        super(firstName, lastName, address, city, state, zipCode);
        copyCSV(s);
    }

    protected Customer() {

    }

    public int getCustomerID() {
        return customerID;
    }

    public void setCustomerID(int customerID) {
        this.customerID = customerID;
    }

    public double getGrossSales() {
        return grossSales;
    }

    public void setGrossSales(double grossSales) {
        this.grossSales = grossSales;
    }

    @Override
    public String toString() {
        return "CustomerID: " + customerID + "\nGrossSales: " + grossSales + super.toString();
    }

    public String toCSV() {
        return this.customerID + "," + this.grossSales + "," + super.toCSV();
    }

    public void copy(Customer c) {
        super.copy(c);
        customerID = c.customerID;
        grossSales = c.grossSales;
    }

    public void copy(int customerId, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
        super.copy(firstName, lastName, address, city, state, zipCode);
        this.customerID = customerId;
        this.grossSales = grossSales;
    }

    public Customer clone() {
        Customer c = new Customer(this.customerID, this.grossSales, this.getFirstName(), this.getLastName(), this.getAddress(), this.getCity(), this.getState(), this.getZipCode());
        return c;    
    }

    public int compareTo(Customer c) {
        int returnValue = 0;

        if (this.customerID > c.customerID) {
            returnValue = -1;
        } else if (this.customerID < c.customerID) {
            returnValue = 1;
        } else {
            returnValue = 0;
        }

        return returnValue;
    }

    public void copyCSV(String s) {
        List<String> list = new ArrayList<>();

        String[] a = s.split(",");

        list = Arrays.asList(a);

        this.copy(Integer.parseInt(list.get(0)), Double.parseDouble(list.get(1)), list.get(2), 
                list.get(3), list.get(4), list.get(5), list.get(6), list.get(7));
    }

}**

public int indexOf(Integer id) {
        int min = 0;
        int max = cl.length - 1; 

        while (min <= max) {
            int mid = (min + max) / 2;
            if (cl[mid] < id) {
                min = mid + 1;
            } else if (cl[mid] > id) {
                max = mid - 1;
            } else {
                return mid;   // target found
            }
        }

        return -(min + 1);    // target not found
    }

Предполагается принять идентификатор клиента и вернуть индекс в массиве, если он найден, и указать точку вставки, если нет.

По сути, у нас есть файл CSV со списком клиентов, и каждому клиенту присваивается идентификатор.У нас есть и класс человека, и класс клиента, который я включил, где мы получаем и устанавливаем все переменные.Наряду с методами toString и toCSV.В последнем классе CustomerList есть несколько методов.Этот, в частности, должен принимать целочисленное значение, такое как 1, 2, 3, 4 и т. Д., И если существует лицо, назначенное этому идентификационному номеру, то он будет возвращать индекс этого человека в созданном массиве.

Но это застревает в операторах сравнения if и else if.

1 Ответ

0 голосов
/ 01 мая 2019

Предполагая, что класс клиента, такой как:

 public class Customer {

private int id;
private String name;

public Customer() {
}

public Customer(int id, String name) {
    this.id = id;
    this.name = name;
}

public int getId() {
    return id;
}

public String getName() {
    return name;
}

public void setId(int id) {
    this.id = id;
}

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

Вы можете вернуть индекс идентификатора в массиве клиентов в статическом методе, передавая оба типа:

    public static int indexOf(Customer[] arr, Customer cust) {
    int min = 0;
    int max = arr.length - 1; 

    while (min <= max) {
        int mid = (min + max) / 2;
        if (arr[mid].getId() < cust.getId()) {
            min = mid + 1;
        } else if (arr[mid].getId() > cust.getId()) {
            max = mid - 1;
        } else {
            return mid;   // target found
        }
    }

    return -(min + 1);    // target not found
}

Youтакже можно преобразовать это в нестатический метод и создать класс для объекта Customer [].Или вы можете использовать его в своем основном (или любом другом методе) следующим образом:

    Customer cl1 = new Customer(1234,"John");
    Customer cl2 = new Customer(1235,"Khal");
    Customer cl3 = new Customer(1236,"John");
    Customer[] clArray = {cl1,cl2,cl3};

    Customer testCustomer = new Customer(1236,"AnyName");
    int index = indexOf(clArray, testCustomer);
    System.out.println(index); //Prints 2, which is the location of 1236 in the array

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

Также я предлагаю изучить ArrayLists, если вы планируете хранить информацию и часто ее менять.Массивы - не самая приятная вещь для обработки.

РЕДАКТИРОВАТЬ: Вот то, что класс CustomerArray должен понравиться в соответствии с вашими комментариями:

public class CustomerArray {

private Customer[] cl;

public CustomerArray() {
}

public CustomerArray(Customer...customers ) {
    this.cl = customers;
}

public Customer[] getCl() {
    return cl;
}

public void setCl(Customer[] cl) {
    this.cl = cl;
}


    public int indexOf(int id) {
    int min = 0;
    int max = cl.length - 1; 

    while (min <= max) {
        int mid = (min + max) / 2;
        if (cl[mid].getId() < id) {
            min = mid + 1;
        } else if (cl[mid].getId() > id) {
            max = mid - 1;
        } else {
            return mid;   // target found
        }
    }

    return -(min + 1);    // target not found
}
}

И затем вы можете использовать его в методе main(или любой другой), подобный этому:

    Customer cl1 = new Customer(1234,"John");
    Customer cl2 = new Customer(1235,"Khal");
    Customer cl3 = new Customer(1236,"John");
    CustomerArray clArray =  new CustomerArray(cl1,cl2,cl3);

    Customer testCustomer = new Customer(1236,"AnyName");
    int index = clArray.indexOf(testCustomer.getId());

    System.out.println(index);

Таким образом, вы объявляете класс CustomerArray, который содержит всех ваших клиентов.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...