Skip to content

Instantly share code, notes, and snippets.

@tipochka
Created September 23, 2016 12:47
Show Gist options
  • Save tipochka/398c273f4d4ac6d22456ccdc55673e13 to your computer and use it in GitHub Desktop.
Save tipochka/398c273f4d4ac6d22456ccdc55673e13 to your computer and use it in GitHub Desktop.
Immutable Point, Line (*). Написать классы: 1. Point: int x, int y. 2. Line: Point start, Point end. Точка и линия должны быть неизменяемыми объектами (Immutable). Выполнить задачи: 1. Создать список разных линий. 2. Посчитать суммарный размер всех линий. 3. Найти самую длинную линию.
package oop.lesson2.homework.lines;
public class Line {
private final Point start;
private final Point stop;
public Line(Point start, Point stop) {
this.start = start;
this.stop = stop;
}
public final double length() {
int catet1 = Math.abs(start.getX() - stop.getX());
int catet2 = Math.abs(start.getY() - stop.getY());
double result = Math.sqrt(Math.pow(catet1, 2) + Math.pow(catet2, 2));
return result;
}
@Override
public String toString() {
return "Line{" +
"start=" + start +
", stop=" + stop +
'}';
}
}
package oop.lesson2.homework.lines;
public class LineRunner {
public static void main(String[] args) {
Line[] lines = {new Line(new Point(3, 3), new Point(6, 6)), new Line(new Point(5, 5), new Point(10, 10))};
System.out.println("Summary Lenght Line: " + sumLength(lines));
System.out.println("Max Line: " + maxLengthLine(lines));
}
public static double sumLength(Line[] lines) {
checkingLines(lines);
double sum = 0;
for(Line line : lines) {
sum += line.length();
}
return sum;
}
public static Line maxLengthLine(Line[] lines) {
checkingLines(lines);
Line max = null;
for(Line line : lines) {
if(max == null || line.length()>max.length()){
max = line;
}
}
return max;
}
public static void checkingLines (Line[] lines) {
if (lines.length == 0) {
throw new IllegalArgumentException("Non Line element");
}
}
}
package oop.lesson2.homework.lines;
public class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public final int getX() {
return x;
}
public final int getY() {
return y;
}
@Override
public String toString() {
return "Point{" +
"x=" + x +
", y=" + y +
'}';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment