Создать пользователя со списком данных - PullRequest
0 голосов
/ 22 февраля 2019

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

Мой вопрос: как мне составить имя клиента и расстояние?

public class TestCustomer {
    public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    ArrayList<String> customersNames = new ArrayList<String>();

        char userInput = ' ';

        System.out.println("A to show all");
        userInput = scan.next().charAt(0);

        if(userInput == 'A') {
            System.out.println("All results ");
            for(int i = 0; i < customersNames.size(); i++) {
                System.out.println(customersNames.get(i));
            }
        }
 }

А вот и мой клиентский класс

public class Customer {
private String name;
private double calories;
private double distance;

public Customer(String name, double distance) {
    this.name = name;
    this.distance = distance;
}

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

public void setCalories(double calories) {
    this.calories = calories;
}
public double getCalories() {
    return calories;
}

public void setDistance(double distance) {
    this.distance = distance;
}
public double getDistance() {
    return distance;
}
}

Ответы [ 2 ]

0 голосов
/ 22 февраля 2019

С некоторыми изменениями в вашем классе Customer, в которых calories и distance будут храниться и массив для каждого дня,

ArrayList<Customer> будет использоваться для хранения спискаклиенты.

Возможное решение:

import java.util.*;

public class Main {
    private static Scanner scan;
    private static ArrayList<Customer> customers;

    public static Customer customerExists(String customerName) {
        for (int i = 0; i < customers.size(); i++) {
            if (customers.get(i).getName().equals(customerName)) {
                return customers.get(i);
            }
        }

        return null;
    }

    public static void addCustomer() {
        System.out.println(">> Add Customer <<\n");

        System.out.print("Enter customer's first name: ");
        String fName = scan.nextLine();

        System.out.print("Enter customer's last name: ");
        String lName = scan.nextLine();

        String fullName = fName + " " + lName;

        Customer existingCustomer = customerExists(fullName);

        if (existingCustomer != null) {
            System.out.println("\nCustomer already on the list. Here's the information: ");
            System.out.println("#\tName\t\tCalories [Mon-Sun]\t\t\t\t\t\tDistance [Mon-Sun]");
            System.out.println(existingCustomer.getName() + "\t" + Arrays.toString(existingCustomer.getCalories()) + "\t" + Arrays.toString(existingCustomer.getDistance()));
            return;
        }

        String[] daysOfWeek = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
        double calories[] = new double[daysOfWeek.length];
        double distance[] = new double[daysOfWeek.length];

        for (int j = 0; j < daysOfWeek.length; j++) {
            System.out.print("Enter calories consumed on " + daysOfWeek[j] + ": ");
            calories[j] = scan.nextDouble();

            System.out.print("Enter distance walked on " + daysOfWeek[j] + ": ");
            distance[j] = scan.nextDouble();
        }

        Customer customer = new Customer(fullName, calories, distance);

        customers.add(customer);

        System.out.println("\nCustomer added successfully!\n");
    }

    public static void showCustomers() {
        System.out.println(">> All Customers <<\n");
        System.out.println("#\tName\t\tCalories [Mon-Sun]\t\t\t\t\t\tDistance [Mon-Sun]");

        for (int i = 0; i < customers.size(); i++) {
            System.out.println(i+1 + "\t" + customers.get(i).getName() + "\t" + Arrays.toString(customers.get(i).getCalories()) + "\t\t\t" + Arrays.toString(customers.get(i).getDistance()));
        }

        System.out.println("\n");
    }

    public static void searchCustomers() {
        System.out.println(">> Search for a Customer <<\n");

        System.out.print("Enter customer's full name: ");
        String fullName = scan.nextLine();


        Customer customer  = customerExists(fullName);
        System.out.println(fullName);

        if (customer == null) {
            System.out.println("\nNo such customer exists.\n");
            return;
        }

        System.out.println("\nCustomer information:\n");
        System.out.println("#\tName\t\tCalories [Mon-Sun]\t\t\t\t\t\tDistance [Mon-Sun]");
        System.out.println(customer.getName() + "\t" + Arrays.toString(customer.getCalories()) + "\t" + Arrays.toString(customer.getDistance()) + "\n");
    }

    public static void main(String[] args) {
        boolean cont = true;
        int option = -1;

        scan = new Scanner(System.in);
        customers = new ArrayList<>();

        do {
            System.out.println("=== Select an Option ===");
            System.out.println("1. Add a customer");
            System.out.println("2. Show all customers");
            System.out.println("3. Search for customer");
            System.out.println("0. Exit");

            System.out.print("\n  > ");

            try {
                option = Integer.parseInt(scan.nextLine());

                System.out.println("\n");

                switch(option) {
                    case 1:
                        addCustomer();
                        break;

                    case 2:
                        showCustomers();
                        break;

                    case 3:
                        searchCustomers();
                        break;

                    case 0:
                        System.out.println("Good Bye!");
                        cont = false;
                        break;

                    default:
                        System.err.println("'" + option + "' is not a valid option. Please try again.\n");
                        break;
                }
            } catch (NumberFormatException e) {
                System.err.println("Invalid option selected.\n");
            }

        } while (cont == true);
    }
}
0 голосов
/ 22 февраля 2019

Используется список клиентов вместо имен клиентов.Для краткости я поставил класс Customer как статический в тестовом классе (все хранится в одном файле).Лучше разделить его, как и вы.

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

Например, при наличии клиентов в HashMap, индексируемых по имени, можно более элегантно получить набор данных в O (1).Но это может быть еще одно улучшение.

Это только список.Поэтому для простоты я добавил равенства, которые делают пользователей равными, если у них одинаковое имя.

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

import java.util.ArrayList;
import java.util.Objects;
import java.util.Scanner;

public class TestCustomer {

    public static class Customer {

        private String name;
        private double calories;
        private double distance;

        public Customer(String name, double calories, double distance) {
            this.name = name;
            this.calories = calories;
            this.distance = distance;
        }

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

        public String getName() {
            return name;
        }

        public void setCalories(double calories) {
            this.calories = calories;
        }

        public double getCalories() {
            return calories;
        }

        public void setDistance(double distance) {
            this.distance = distance;
        }

        public double getDistance() {
            return this.distance;
        }

        @Override
        public int hashCode() {
            int hash = 5;
            hash = 71 * hash + Objects.hashCode(this.name);
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            return Objects.equals(this.name, ((Customer)obj).name);
        }

    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        ArrayList<Customer> customers = new ArrayList<>();

        char userInput = ' ';

        while (userInput != 'q') {
            System.out.println("Press 'a' to show all customers or press 's' to search for customer ");
            userInput = scan.next().charAt(0);
            userInput = Character.toUpperCase(userInput);

            if (userInput == 'A') {
                System.out.println("Here's the list of all customers: ");
                for (int i = 0; i < customers.size(); i++) {
                    System.out.println(customers.get(i).getName());
                }
                // here I should show the list of all customers and their data
            } else if (userInput == 'S') {
                System.out.println("You selected to search for a customer");
                createCustomer(customers);
            }
        }
    }

    public static ArrayList<Customer> createCustomer(ArrayList<Customer> customers) {
        Scanner scan2 = new Scanner(System.in);
        System.out.println("Enter customer's first name: ");
        String fName = scan2.next();
        System.out.println("Enter customer's last name: ");
        String lName = scan2.next();
        String fullName = fName + " " + lName;
        Customer newCustomer = new Customer(fullName,0,0); 
        if (customers.contains(newCustomer)) {
            newCustomer=customers.get(customers.indexOf(newCustomer));
            System.out.println("Customer already on the list. Here's the information: ");
            System.out.println(fullName + " " + newCustomer.distance + " " + newCustomer.calories );
        } else{
            System.out.println("Customer not found. Would you like to create a new customer? y/n ");
            char createUserPrompt = scan2.next().charAt(0);
            if (createUserPrompt == 'y') {
                String[] daysOfWeek = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
                for (String daysOfWeek1 : daysOfWeek) {
                    System.out.println("Enter calories consumed on " + daysOfWeek1);
                    newCustomer.calories = scan2.nextDouble();
                    System.out.println("Enter distance walked on " + daysOfWeek1);
                    newCustomer.distance = scan2.nextDouble();
                }
                customers.add(newCustomer);
            } else if (createUserPrompt == 'n') {
                System.out.println("User will not be added.");
            }
        }
        return customers;
    }
}

Пример прогона:

Press 'a' to show all customers or press 's' to search for customer 
a
Here's the list of all customers: 
Press 'a' to show all customers or press 's' to search for customer 
s
You selected to search for a customer
Enter customer's first name: 
kai
Enter customer's last name: 
last
Customer not found. Would you like to create a new customer? y/n 
y
Enter calories consumed on Monday
5
Enter distance walked on Monday
5
Enter calories consumed on Tuesday
5
Enter distance walked on Tuesday
5
Enter calories consumed on Wednesday
5
Enter distance walked on Wednesday
5
Enter calories consumed on Thursday
5
Enter distance walked on Thursday
5
Enter calories consumed on Friday
5
Enter distance walked on Friday
5
Enter calories consumed on Saturday
5
Enter distance walked on Saturday
5
Enter calories consumed on Sunday
5
Enter distance walked on Sunday
5
Press 'a' to show all customers or press 's' to search for customer 
a
Here's the list of all customers: 
kai last
Press 'a' to show all customers or press 's' to search for customer 
s
You selected to search for a customer
Enter customer's first name: 
kai
Enter customer's last name: 
last
Customer already on the list. Here's the information: 
kai last 5.0 5.0
Press 'a' to show all customers or press 's' to search for customer 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...