sem04 almost

This commit is contained in:
Ivan I. Ovchinnikov 2022-12-30 13:33:28 +03:00
parent e3ac8548f5
commit 1b865320a6
4 changed files with 388 additions and 7 deletions

Binary file not shown.

View File

@ -170,8 +170,78 @@ private static final class RowMismatchException extends RuntimeException {
\end{enumerate}
\textbf{Вариант исполнения класса в приложении \ref{appendix:ct1}}
\begin{lstlisting}[language=Java,style=JCodeStyle,caption={Создание объекта класса}]
\textbf{Вариант маршрута решения задачи}
\begin{lstlisting}[language=Java,style=JCodeStyle,caption={Описание класса исключения логина}]
public static class WrongLoginException extends RuntimeException {
private int currentLength;
public WrongLoginException(int currentLength) {
super();
this.currentLength = currentLength;
}
@Override
public String getMessage() {
return String.format("Your login is of incorrect length, expected < 20, given %d.",
currentLength);
}
}
\end{lstlisting}
\begin{lstlisting}[language=Java,style=JCodeStyle,caption={Формирование сообщения для класса исключения пароля}]
public static class WrongPasswordException extends RuntimeException {
private int currentLength;
private boolean matchConfirm;
public WrongPasswordException(int currentLength, boolean matchConfirm) {
super();
this.currentLength = currentLength;
this.matchConfirm = matchConfirm;
}
@Override
public String getMessage() {
boolean badlen = currentLength <= 20;
return String.format("Your password is of %scorrect length%s %d. Password %smatch the confirmation.",
((badlen) ? "in" : ""),
((badlen) ? ", expected > 20, given" : ","),
currentLength,
(matchConfirm) ? "" : "doesn't ");
}
}
\end{lstlisting}
\begin{lstlisting}[language=Java,style=JCodeStyle,caption={Создание тестовой среды}]
public static void main(String[] args) {
String[][] credentials = {
{"ivan", "1i2v3a4n5i6v7a8n91011", "1i2v3a4n5i6v7a8n91011"}, //correct
{"1i2v3a4n5i6v7a8n91011", "", ""}, //wrong login length
{"ivan", "1i2v3a4n5i6v7a8n91011", "1i2v3a4n5"}, //confirm mismatch
{"ivan", "1i2v3a4n5", "1i2v3a4n5"},//wrong password length
{"ivan", "1i2v3a4n5", "1i"} //wrong password length and confirm mismatch
};
for (int i = 0; i < credentials.length; i++) {
try {
System.out.println(checkCredentials(credentials[i][0], credentials[i][1], credentials[i][2]));
} catch (WrongLoginException e) {
e.printStackTrace();
} catch (WrongPasswordException e) {
System.out.println(e.getMessage());
}
}
}
\end{lstlisting}
\begin{lstlisting}[language=Java,style=JCodeStyle,caption={Метод проверки}]
public static boolean checkCredentials(String login, String password, String confirmPassword) {
boolean conf = password.equals(confirmPassword);
int llen = login.length();
int plen = password.length();
if (llen >= 20)
throw new WrongLoginException(llen);
else if (plen < 20 || !conf)
throw new WrongPasswordException(plen, conf);
else
return true;
}
\end{lstlisting}
\end{itemize}
\subsubsection{Задание 2}
@ -200,7 +270,87 @@ private static final class RowMismatchException extends RuntimeException {
\end{enumerate}
\textbf{Вариант исполнения класса в приложении \ref{appendix:ct1}}
\begin{lstlisting}[language=Java,style=JCodeStyle,caption={Создание объекта класса}]
\textbf{Вариант маршрута решения задачи}
\begin{lstlisting}[language=Java,style=JCodeStyle,caption={Создание базовых классов (идентично)}]
private static class Item {
String name;
int cost;
public Item(String name, int cost) {
this.name = name;
this.cost = cost;
}
@Override
public String toString() {
return "Item{name='" + name + "', cost=" + cost + "}";
}
}
\end{lstlisting}
\begin{lstlisting}[language=Java,style=JCodeStyle,caption={Создание пользовательских исключений}]
public static class CustomerException extends RuntimeException {
public CustomerException(String message) {
super(message);
}
}
\end{lstlisting}
\begin{lstlisting}[language=Java,style=JCodeStyle,caption={Создание массивов}]
private final static Customer[] people = {
new Customer("Ivan", 20, "+1-222-333-44-55"),
new Customer("Petr", 30, "+2-333-444-55-66"),
};
private final static Item[] items = {
new Item("Ball", 100),
new Item("Sandwich", 1000),
new Item("Table", 10000),
new Item("Car", 100000),
new Item("Rocket", 10000000)
};
private static Order[] orders = new Order[5];
\end{lstlisting}
\begin{lstlisting}[language=Java,style=JCodeStyle,caption={Описание тестовой среды}]
Object[][] info = {
{people[0], items[0], 1}, //good
{people[1], items[1], -1}, //bad amount -1
{people[0], items[2], 150}, //bad amount >100
{people[1], new Item("Flower", 10), 1}, //no item
{new Customer("Fedor", 40, "+3-444-555-66-77"), items[3], 1}, //no customer
};
int capacity = 0;
int i = 0;
while (capacity != orders.length - 1 || i != info.length) {
try {
orders[capacity] = buy((Customer) info[i][0], (Item) info[i][1], (int) info[i][2]);
capacity++;
} catch (ProductException e) {
e.printStackTrace();
} catch (AmountException e) {
orders[capacity++] = buy((Customer) info[i][0], (Item) info[i][1], 1);
} catch (CustomerException e) {
throw new RuntimeException(e);
} finally {
System.out.println("Orders made: " + capacity);
}
++i;
}
\end{lstlisting}
\begin{lstlisting}[language=Java,style=JCodeStyle,caption={Написание и отладка основного метода}]
private static boolean isInArray(Object[] arr, Object o) {
for (int i = 0; i < arr.length; i++)
if (arr[i].equals(o)) return true;
return false;
}
public static Order buy(Customer who, Item what, int howMuch) {
if (!isInArray(people, who))
throw new CustomerException("Unknown customer: " + who);
if (!isInArray(items, what))
throw new ProductException("Unknown item: " + what);
if (howMuch < 0 || howMuch > 100)
throw new AmountException("Incorrect amount: " + howMuch);
return new Order(who, what, howMuch);
}
\end{lstlisting}
\end{itemize}
@ -221,10 +371,49 @@ private static final class RowMismatchException extends RuntimeException {
\textbf{Все варианты решения приведены в тексте семинара выше}
\item [15 мин] 1. В класс покупателя добавить перечисление с гендерами, добавить в сотрудника свойство «пол» со значением созданного перечисления. Добавить геттеры, сеттеры.
\begin{lstlisting}[language=Java,style=JCodeStyle,caption={}]
\begin{lstlisting}[language=Java,style=JCodeStyle,caption={Свойства сотрудника}]
enum Genders{MALE, FEMALE};
// ...
Genders gender;
public Employee(String name, String midName, String surName, String phone, String position, int salary, int birth, Genders gender) {
// ...
this.gender = gender;
}
public Genders getGender() {
return gender;
}
public void setGender(Genders gender) {
this.gender = gender;
}
\end{lstlisting}
\item [20-25 мин] 2. Добавить в основную программу перечисление с праздниками (Новый Год, 8 марта, 23 февраля), написать метод, принимающий массив сотрудников, поздравляющий всех сотрудников с Новым Годом, женщин с 8 марта, а мужчин с 23 февраля.
\begin{lstlisting}[language=Java,style=JCodeStyle,caption={}]
\item [20-25 мин] 2. Добавить в основную программу перечисление с праздниками (нет праздника, Новый Год, 8 марта, 23 февраля), написать метод, принимающий массив сотрудников, поздравляющий всех сотрудников с Новым Годом, женщин с 8 марта, а мужчин с 23 февраля, если сегодня соответствующий день.
\begin{lstlisting}[language=Java,style=JCodeStyle,caption={Праздники}]
enum Parties{NONE, NEW_YEAR, MARCH_8, FEB_23}
private static final Parties today = Parties.NONE;
private static void celebrate(Employee[] emp) {
for (int i = 0; i < emp.length; i++) {
switch (today) {
case NEW_YEAR:
System.out.println(emp[i].name + ", happy New Year!");
break;
case FEB_23:
if (emp[i].gender == Employee.Genders.MALE)
System.out.println(emp[i].name + ", happy February 23rd!");
break;
case MARCH_8:
if (emp[i].gender == Employee.Genders.FEMALE)
System.out.println(emp[i].name + ", happy march 8th!");
break;
default:
System.out.println(emp[i].name + ", celebrate this morning!");
}
}
}
\end{lstlisting}
\end{enumerate}
\end{itemize}

View File

@ -0,0 +1,68 @@
package ru.gb.jcore;
public class SignInWorker {
public static class WrongPasswordException extends RuntimeException {
private int currentLength;
private boolean matchConfirm;
public WrongPasswordException(int currentLength, boolean matchConfirm) {
super();
this.currentLength = currentLength;
this.matchConfirm = matchConfirm;
}
@Override
public String getMessage() {
boolean badlen = currentLength <= 20;
return String.format("Your password is of %scorrect length%s %d. Password %smatch the confirmation.",
((badlen) ? "in" : ""),
((badlen) ? ", expected > 20, given" : ","),
currentLength,
(matchConfirm) ? "" : "doesn't ");
}
}
public static class WrongLoginException extends RuntimeException {
private int currentLength;
public WrongLoginException(int currentLength) {
super();
this.currentLength = currentLength;
}
@Override
public String getMessage() {
return String.format("Your login is of incorrect length, expected < 20, given %d.",
currentLength);
}
}
public static boolean checkCredentials(String login, String password, String confirmPassword) {
boolean conf = password.equals(confirmPassword);
int llen = login.length();
int plen = password.length();
if (llen >= 20)
throw new WrongLoginException(llen);
else if (plen < 20 || !conf)
throw new WrongPasswordException(plen, conf);
else
return true;
}
public static void main(String[] args) {
String[][] credentials = {
{"ivan", "1i2v3a4n5i6v7a8n91011", "1i2v3a4n5i6v7a8n91011"}, //correct
{"1i2v3a4n5i6v7a8n91011", "", ""}, //wrong login length
{"ivan", "1i2v3a4n5i6v7a8n91011", "1i2v3a4n5"}, //confirm mismatch
{"ivan", "1i2v3a4n5", "1i2v3a4n5"},//wrong password length
{"ivan", "1i2v3a4n5", "1i"} //wrong password length and confirm mismatch
};
for (int i = 0; i < credentials.length; i++) {
try {
System.out.println(checkCredentials(credentials[i][0], credentials[i][1], credentials[i][2]));
} catch (WrongLoginException e) {
e.printStackTrace();
} catch (WrongPasswordException e) {
System.out.println(e.getMessage());
}
}
}
}

View File

@ -0,0 +1,124 @@
package ru.gb.jcore;
public class Shop {
/**
* Вызвать метод совершения покупки несколько раз таким образом,
* чтобы заполнить массив покупок возвращаемыми значениями.
* Обработать исключения следующим образом (в заданном порядке):
* */
private static class Customer {
String name;
int age;
String phone;
public Customer(String name, int age, String phone) {
this.name = name;
this.age = age;
this.phone = phone;
}
@Override
public String toString() {
return "Customer{name='" + name + '\'' +
", age=" + age + ", phone='" + phone + "'}";
}
}
private static class Item {
String name;
int cost;
public Item(String name, int cost) {
this.name = name;
this.cost = cost;
}
@Override
public String toString() {
return "Item{name='" + name + "', cost=" + cost + "}";
}
}
private static class Order {
Customer customer;
Item item;
int amount;
public Order(Customer customer, Item item, int amount) {
this.customer = customer;
this.item = item;
this.amount = amount;
}
@Override
public String toString() {
return "Order{customer=" + customer +
", item=" + item + ", amount=" + amount + "}";
}
}
public static class CustomerException extends RuntimeException {
public CustomerException(String message) { super(message); }
}
public static class ProductException extends RuntimeException {
public ProductException(String message) { super(message); }
}
public static class AmountException extends RuntimeException {
public AmountException(String message) { super(message); }
}
private final static Customer[] people = {
new Customer("Ivan", 20, "+1-222-333-44-55"),
new Customer("Petr", 30, "+2-333-444-55-66"),
};
private final static Item[] items = {
new Item("Ball", 100),
new Item("Sandwich", 1000),
new Item("Table", 10000),
new Item("Car", 100000),
new Item("Rocket", 10000000)
};
private static Order[] orders = new Order[5];
private static boolean isInArray(Object[] arr, Object o) {
for (int i = 0; i < arr.length; i++)
if (arr[i].equals(o)) return true;
return false;
}
public static Order buy(Customer who, Item what, int howMuch) {
if (!isInArray(people, who))
throw new CustomerException("Unknown customer: " + who);
if (!isInArray(items, what))
throw new ProductException("Unknown item: " + what);
if (howMuch < 0 || howMuch > 100)
throw new AmountException("Incorrect amount: " + howMuch);
return new Order(who, what, howMuch);
}
public static void main(String[] args) {
Object[][] info = {
{people[0], items[0], 1}, //good
{people[1], items[1], -1}, //bad amount -1
{people[0], items[2], 150}, //bad amount >100
{people[1], new Item("Flower", 10), 1}, //no item
{new Customer("Fedor", 40, "+3-444-555-66-77"), items[3], 1}, //no customer
};
int capacity = 0;
int i = 0;
while (capacity != orders.length - 1 || i != info.length) {
try {
orders[capacity] = buy((Customer) info[i][0], (Item) info[i][1], (int) info[i][2]);
capacity++;
} catch (ProductException e) {
e.printStackTrace();
} catch (AmountException e) {
orders[capacity++] = buy((Customer) info[i][0], (Item) info[i][1], 1);
} catch (CustomerException e) {
throw new RuntimeException(e);
} finally {
System.out.println("Orders made: " + capacity);
}
++i;
}
}
}