Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/master'
Browse files Browse the repository at this point in the history
Conflicts:
	README.md
  • Loading branch information
dennysem committed Nov 17, 2014
2 parents 6b78f44 + 10157be commit df4cd99
Show file tree
Hide file tree
Showing 1,317 changed files with 86,157 additions and 735 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
.DS_Store
*.class

# Mobile Tools for Java (J2ME)
Expand All @@ -17,6 +18,8 @@ jars

.classpath
.project
workbench.xmi
*.swp

.settings
.checkstyle
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,35 @@
# Программирование на языке JAVA
# Программирование на языке JAVA

Курс лекций и семинаров для студентов второго курса ФизТеха, факультет
[ФИВТ](http://fivt.fizteh.ru) на 2014 год.

## Семинары
В папке [tasks](tasks) находятся описания заданий на
семинары. Для написания программ необходимо руководствоваться [соглашениями
по оформлению кода](http://www.oracle.com/technetwork/java/codeconv-138413.html)
по оформлению кода](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html)
от Oracle (Code Conventions).

В документе [github-workflow](github-workflow.md) описаны
общие правила по ведению задач на github, а также упрощение жизни с помощью утилиты
[checkstyle](http://checkstyle.sourceforge.net/), которая проверяет код на соответствие
Code Conventions.

## Лекции
1. [Java, JVM, примитивные типы](https://yadi.sk/d/_ZgbGf9NbXraZ)
2. [Object, String, исключения](https://yadi.sk/d/MCu6krbtbXrgZ)
3. [IO Stream, инициализация объектов, enum](https://yadi.sk/d/MinWJhG0bteEr)
4. [Лямбды, аннотации, обобщения, коллекции](https://yadi.sk/d/hxkoP81rbteTp)
5. [Reflection, Proxy, JUnit](https://yadi.sk/i/Ku-C6VYOc4icJ)
6. [Сериализация, XML, JSON](https://yadi.sk/d/8upuEG2ecRknU)
7. [Многопоточность](https://yadi.sk/i/FsBB-AXVcRkoH)
8. [Многопоточность](https://yadi.sk/i/IY2kKLoacgaBr)

## Список литературы
* Брюс Эккель — Философия Java (Thinking in Java)
* Brian Goetz — Java Concurrency in Practive (продвинутая книжка
по многопоточности в Java)
* [Спецификации по JVM и JLS](http://docs.oracle.com/javase/specs/index.html)
* [Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html)

## Успеваемость
[Таблица на Google Docs](https://docs.google.com/spreadsheet/ccc?key=0Ag7dwrMmZBKedGk1Q1RfSXh1RzZyeEJhaE94dW1CaGc&usp=sharing)
Binary file added lib/hamcrest-core-1.3.jar
Binary file not shown.
34 changes: 34 additions & 0 deletions src/ru/fizteh/fivt/proxy/LoggingProxyFactory.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package ru.fizteh.fivt.proxy;

import java.io.Writer;

/**
* Представляет интерфейс для создания обёрток вокруг интерфейсов.
*/
public interface LoggingProxyFactory {

/**
* Создаёт класс-обёртку вокруг объекта <code>implementation</code>, которая при вызове
* методов интерфейса <code>interfaceClass</code> выполняет логирование аргументов и результата
* вызова методов.
*
* Класс-обёртка не имеет права выбрасывать свои исключения, но обязана выбрасывать те же самые
* исключения, что выбрасывает оригинальный класс.
*
* Класс-обёртка должен быть потокобезопасным.
*
* @param writer Объект, в который ведётся запись лога.
* @param implementation Объект, реализующий интерфейс <code>interfaceClass</code>.
* @param interfaceClass Класс интерфейса, методы которого должны выполнять запись в лог.
*
* @return Объект, реализующий интерфейс <code>interfaceClass</code>, при вызове методов которого
* выполняется запись в лог.
*
* @throws IllegalArgumentException Если любой из переданных аргументов null или имеет некорректное значение.
*/
Object wrap(
Writer writer,
Object implementation,
Class<?> interfaceClass
);
}
4 changes: 1 addition & 3 deletions src/ru/fizteh/fivt/storage/strings/Table.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import ru.fizteh.fivt.students.semenenko_denis.MultiFileHashMap.LoadOrSaveException;

import java.util.List;

/**
* @author Fedor Lavrentyev
* @author Dmitriy Komanov
Expand Down Expand Up @@ -53,7 +52,6 @@ public interface Table {
* @return Количество ключей в таблице.
*/
int size();

/**
* Выполняет фиксацию изменений.
*
Expand All @@ -67,7 +65,6 @@ public interface Table {
* @return Количество отменённых ключей.
*/
int rollback();

/**
* Выводит список ключей таблицы
*
Expand All @@ -77,3 +74,4 @@ public interface Table {


}

1 change: 0 additions & 1 deletion src/ru/fizteh/fivt/storage/strings/TableProvider.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
package ru.fizteh.fivt.storage.strings;

/**
* @author Fedor Lavrentyev
* @author Dmitriy Komanov
Expand Down
3 changes: 1 addition & 2 deletions src/ru/fizteh/fivt/storage/strings/TableProviderFactory.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
package ru.fizteh.fivt.storage.strings;

/**
* Представляет интерфейс для создание экземпляров {@link TableProvider}. Предполагается, что реализация интерфейса
* фабрики будет иметь публичный конструктор без параметров.
Expand All @@ -8,7 +7,7 @@
* @author Dmitriy Komanov
*/
public interface TableProviderFactory {

/**
* Возвращает объект для работы с базой данных.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package ru.fizteh.fivt.students.AlexeyZhuravlev.calculator;

import java.util.EmptyStackException;
import java.util.Stack;

/**
* @author AlexeyZhuravlev
*/

public final class BinaryMinusOperator extends Lexeme {

@Override
protected int priority() {
return 1;
}

@Override
protected void makeOperation(Stack<NumberLexeme> results) throws Exception {
try {
NumberLexeme second = results.pop();
NumberLexeme first = results.pop();
results.push(new NumberLexeme(first.value.subtract(second.value)));
} catch (EmptyStackException e) {
throw new Exception("Not enough arguments for binary minus operation");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package ru.fizteh.fivt.students.AlexeyZhuravlev.calculator;

import java.math.BigDecimal;
import java.util.StringTokenizer;
import java.util.Stack;

/**
* @author AlexeyZhuravlev
*/

public class CalculatorMain {

public static void main(String[] args) {
if (args.length < 1) {
System.err.println("First argument(expression) expected.");
System.exit(1);
}
try {
BigDecimal result = calculate(args[0]);
System.out.println(result);
} catch (Exception e) {
System.err.println(e.getMessage());
System.exit(2);
}
}

private static BigDecimal calculate(String inputString) throws Exception {
inputString = "(" + inputString.replaceAll(" ", "") + ")";
inputString = markUnaryMinuses(inputString, '~');
StringTokenizer tokenizer = new StringTokenizer(inputString, "+-*/()~", true);
Stack<NumberLexeme> results = new Stack<NumberLexeme>();
Stack<Lexeme> operations = new Stack<Lexeme>();
while (tokenizer.hasMoreTokens()) {
String t = tokenizer.nextToken();
Lexeme lex = Lexeme.fromString(t);
lex.addLexeme(results, operations);
}
if (!operations.isEmpty()) {
throw new Exception("No parenthesis balance");
}
if (results.isEmpty()) {
throw new Exception("No numbers in equations");
}
if (results.size() > 1) {
throw new Exception("Not enough operators for these numbers");
}
return results.peek().value;
}

private static String markUnaryMinuses(String s, char newSymbol) throws Exception {
String result = "(";
String correctSymbols = "01234567890.+-*/()";
for (int i = 1; i < s.length(); i++) {
char current = s.charAt(i);
char previous = s.charAt(i - 1);
if (correctSymbols.indexOf(current) == -1) {
throw new Exception("Incorrect symbol in equation");
}
if (current == ')' && previous == '(') {
throw new Exception("Empty parenthesis");
}
if (current == '-' && previous != ')' && !Character.isDigit(previous)) {
current = newSymbol;
}
result = result + current;
}
return result;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package ru.fizteh.fivt.students.AlexeyZhuravlev.calculator;

import java.util.EmptyStackException;
import java.util.Stack;

/**
* @author AlexeyZhuravlev
*/

public final class CloseParenthesisOperator extends Lexeme {

@Override
protected int priority() throws Exception {
throw new Exception("Logical error: close parenthesis is never checked for priority");
}

@Override
protected void makeOperation(Stack<NumberLexeme> results) throws Exception {
throw new Exception("Logical error: close parenthesis can't make any operation");
}

@Override
public void addLexeme(Stack<NumberLexeme> results, Stack<Lexeme> operations) throws Exception {
try {
while (operations.peek().priority() != 0) {
Lexeme operation = operations.pop();
operation.makeOperation(results);
}
} catch (EmptyStackException e) {
throw new Exception("No parenthesis balance");
}
operations.pop();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package ru.fizteh.fivt.students.AlexeyZhuravlev.calculator;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Stack;
import java.util.EmptyStackException;

/**
* @author AlexeyZhuravlev
*/

public final class DivideOperator extends Lexeme {

@Override
protected int priority() {
return 2;
}

@Override
protected void makeOperation(Stack<NumberLexeme> results) throws Exception {
try {
NumberLexeme second = results.pop();
NumberLexeme first = results.pop();
if (second.value.equals(BigDecimal.ZERO)) {
throw new Exception("Division by zero");
}
results.push(new NumberLexeme(first.value.divide(second.value, MathContext.DECIMAL128)));
} catch (EmptyStackException e) {
throw new Exception("Not enough arguments for divide operation");
}
}
}
48 changes: 48 additions & 0 deletions src/ru/fizteh/fivt/students/AlexeyZhuravlev/calculator/Lexeme.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package ru.fizteh.fivt.students.AlexeyZhuravlev.calculator;

import java.util.Stack;
import java.util.EmptyStackException;

/**
* @author AlexeyZhuravlev
*/

public abstract class Lexeme {

public static Lexeme fromString(String s) throws Exception {
if (s.length() < 1) {
throw new Exception("Empty string is not a lexeme");
}
switch(s.charAt(0)) {
case '+': return new PlusOperator();
case '-': return new BinaryMinusOperator();
case '*': return new MultiplyOperator();
case '/': return new DivideOperator();
case '~': return new UnaryMinusOperator();
case '(': return new OpenParenthesisOperator();
case ')': return new CloseParenthesisOperator();
default:
try {
return new NumberLexeme(s);
} catch (NumberFormatException e) {
throw new Exception(s + " - incorrect lexeme");
}
}
}

protected abstract int priority() throws Exception;

protected abstract void makeOperation(Stack<NumberLexeme> results) throws Exception;

public void addLexeme(Stack<NumberLexeme> results, Stack<Lexeme> operations) throws Exception {
try {
while (operations.peek().priority() >= this.priority()) {
Lexeme operation = operations.pop();
operation.makeOperation(results);
}
operations.push(this);
} catch (EmptyStackException e) {
throw new Exception("No parenthesis balance");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package ru.fizteh.fivt.students.AlexeyZhuravlev.calculator;

import java.util.Stack;
import java.util.EmptyStackException;

/**
* @author AlexeyZhuravlev
*/

public final class MultiplyOperator extends Lexeme {

@Override
protected int priority() {
return 2;
}

@Override
protected void makeOperation(Stack<NumberLexeme> results) throws Exception {
try {
NumberLexeme second = results.pop();
NumberLexeme first = results.pop();
results.push(new NumberLexeme(first.value.multiply(second.value)));
} catch (EmptyStackException e) {
throw new Exception("Not enough arguments for multiply operation");
}
}
}
Loading

0 comments on commit df4cd99

Please sign in to comment.