Классы в Java
Создание собственных классов в Java (начало)
1. Задание
Создать статический метод, который будет иметь два целочисленных параметра a и b, и в качестве своего значения возвращать случайное целое число из отрезка [a;b]. C помощью данного метода заполнить массив из 20 целых чисел и вывести его на экран.
public class one { public static void pr(){ System.out.println(); } public static int rand(int a, int b) { return (int)(Math.random()*(b-a+1)+(a)); } public static void main(String[] args) { int[] mas = new int[20]; int a = 10, b = 15; for(int i=0; i<mas.length; i++) { mas[i] = rand(a, b); System.out.print(mas[i]+" "); } pr(); } }
2. Задание
Создать метод, который будет выводить указанный массив на экран в строку. С помощью созданного метода и метода из предыдущей задачи заполнить 5 массивов из 10 элементов каждый случайными числами и вывести все 5 массивов на экран, каждый на отдельной строке.
public class two { public static void pr(){ System.out.println(); } public static int rand(int a, int b) { return (int)(Math.random()*(b-a+1)+(a)); } public static void arr(int[] mas) { for(int i=0; i<mas.length; i++) { System.out.print(mas[i]+" "); } } public static void main(String[] args) { int[] mas1 = new int[10], mas2 = new int[10], mas3 = new int[10], mas4 = new int[10], mas5 = new int[10]; int a = 10, b = 15; for(int i=0; i<mas1.length; i++) { mas1[i] = rand(a, b); } arr(mas1); pr(); for(int i=0; i<mas2.length; i++) { mas2[i] = rand(a, b); } arr(mas2); pr(); for(int i=0; i<mas3.length; i++) { mas3[i] = rand(a, b); } arr(mas3); pr(); for(int i=0; i<mas4.length; i++) { mas4[i] = rand(a, b); } arr(mas4); pr(); for(int i=0; i<mas5.length; i++) { mas5[i] = rand(a, b); } arr(mas5); pr(); } }
3. Задание
Создать метод, который будет сортировать указанный массив по возрастанию любым известным вам способом.
public class three { public static void pr(){ System.out.println(); } public static int rand(int a, int b) { return (int)(Math.random()*(b-a+1)+(a)); } public static void arr(int[] mas) { for(int i=0; i<mas.length; i++) { System.out.print(mas[i]+" "); } } public static void sort(int[] a) { for (int i = a.length - 1; i >= 2; i--) { boolean sorted = true; for (int j = 0; j < i; j++) { if (a[j] > a[j+1]) { int temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; sorted = false; } } if(sorted) { break; } } } public static void main(String[] args) { int[] mas = new int[10]; int a = 10, b = 15; for(int i=0; i<mas.length; i++) { mas[i] = rand(a, b); } arr(mas); sort(mas); pr(); arr(mas); } }
4. Задание
В массиве хранится 7 явно заданных текстовых строк. Создать программу, которая отсортирует и выведет на экран строки в алфавитном порядке. Например, если были даны такие строки:
Пушкин
Лермонтов
Некрасов
Толстой Л. Н.
Толстой А. Н.
Есенин
Паустовский
Программа должна вывести на экран:
Есенин
Лермонтов
Некрасов
Паустовский
Пушкин
Толстой А. Н.
Толстой Л. Н.
Указание: прежде всего надо создать метод, устанавливающий отношения порядка для двух строк, переданных методу через аргументы.
public class four { public static void pr(){ System.out.println(); } public static void pr(String a){ System.out.println(a); } /*-----------Вывод массива на экран-----------*/ public static void arr(String[] mas) { for(int i=0; i<mas.length; i++) { System.out.println(mas[i]); } } /*--------------------------------------------*/ /*------------------------------SORT(Сортировка)------------------------------------------*/ public static void sort(String[] a) { for (int i = a.length - 1; i >= 2; i--) { boolean sorted = true; for (int j = 0; j < i; j++) { if (compare(a[j], a[j+1])>0) {//Используем функцию compare для сравнения двух слов String temp = a[j+1]; a[j+1] = a[j]; a[j] = temp; sorted = false; } } if(sorted) { break; } } } /*------------------------------COMPARE(Сравнение)------------------------------------------*/ public static int compare(String word1, String word2) { word1 = word1.toLowerCase();//Переводим в нижний регистр word2 = word2.toLowerCase();//Переводим в нижний регистр //Задаем массивы, где будут храниться буквы слов int[] mas1 = new int[word1.length()]; int[] mas2 = new int[word2.length()]; //Заполняем массивы буквами (точнее порядковыми номерами этих букв) for(int i=0; i<mas1.length; i++) { char b = word1.charAt(i);//Цепляем из строки букву с порядковым номером i и сохраняем ее в переменную b int k = (int)b;//Берем порядковый номер этой буквы mas1[i] = k;//Записываем этот порядковый номер в массив } //Аналогично, только для другого слова for(int i=0; i<mas2.length; i++) { char b = word2.charAt(i); int k = (int)b; mas2[i] = k; } int i = 0, bool = 0; //Пропускаем все одинаковые буквы в слове, они нас не интересуют, пока не попадутся не равные while(mas1[i]==mas2[i]) { i++; if(i>=mas1.length||i>=mas2.length) {//Счетчик уже больше границ одного из массива, все остальное равно => сравниваем уже длину слова if(mas1.length==mas2.length) { break;//Строки равны } else if(mas1.length<mas2.length) { bool = -1;//Строка mas1 лежит выше по алфавиту, чем строка mas2 break; } else { bool = 1;//Строка mas1 лежит ниже по алфавиту, чем строка mas2 break; } } } if(mas1.length>1&&mas2.length>1) {//Описываем, что делать программе, если строки состоят более, чем из одной буквы //Напомню, что мы уже исключили равные буквы, поэтому нам достаточно //сравнить только эти две неравные буквы, если буква 1-го слова больше буквы 2-го слова, то 1-е слово лежит ниже второго if(mas1[i]>mas2[i]) { bool = 1; //Аналогично, только тут идет проверка на то, лежит ли 1-е слово выше по алфавиту } else if(mas1[i]<mas2[i]) { bool = -1; } } else { //Остался вариант, когда слова представляют из себя буквы, тогда просто сравниваем нулевые элементы массивов //оба эти массива состаят из одного элемента с индексом 0 //Ниже по алфавиту if(mas1[0]>mas2[0]) { bool = 1; //Выше по алфавиту }else if(mas1[0]<mas2[0]) { bool = -1; } } return bool;//Возвращаем значение переменной bool. Если значение отрицательное, то первое слово //лежит выше по алфавиту, чем второе. Если значение положительное, то ситуация обратна: первое //слово лежит ниже по алфавиту, чем второе. Если 0, то эти слова равны } /*-------------------------------------------------------------------------------*/ public static void main(String[] args) { //Задаем исходный массив String[] a = {"Pushkin", "Lermontov", "Nekrasov", "Tolstoj L. N.", "Tolstoj A. N.", "Esenin", "Paystovskij","a","Av"}; sort(a);//Сортируем массив arr(a);//Выводим массив на экран pr();//Переводим на другую строку } }
Рекурсия
1-3. Задания
- Выясните экспериментальном путём, начиная с какого элемента последовательности Фибоначчи, вычисление с использованием рекурсии становится неприемлемым (занимает более минуты по времени).
- Создайте гибридный метод, для небольших n вычисляющий n-ое число Фибоначчи с помощью рекурсии, а для значений, превышающих выясненное вами в предыдущей задаче пороговое n, вычисляющий n-ое число Фибоначчи с помощью итерационного алгоритма (цикла, в рамках которого будут сохраняться значения двух предыдущих элементов последовательности).
- Подсчитайте, сколько раз потребуется повторно вычислить четвёртый элементы последовательности Фибоначчи для вычисления пятнадцатого элемента.
public class one { public static void ln(String a) { System.out.println(a); } static long fib (int n) { if (n==1 || n == 2) { return 1; } return fib (n-2) + fib (n-1); } static long fibo(int n) { //lim(fib(n)) = 47 if(n < 47) { long z = fib(n); return z; } else { long n1 = 1,n2 = 1,s=0; for(int i = 0; i<n; i++){ if(i%2==0) { s = n1+n2; n1 = s; } else { s = n1+n2; n2 = s; } } return s; } } public static void main(String[] args) { int f = 15; long d = fibo(f); f = 4; long d1 = fibo(f); int k = (int)(d/d1); ln("Zadanije 1: Na 48 nomere secundomer pokazal 1:00.76 (1 minuta 0.76 sekund)"); System.out.println("Zadanije 2: "+fibo(100)); System.out.println("Zadanije 3: "+k+" raz"); } }
Создание классов (продолжение). Класс Object
1. Задание
Создайте в классе метод, который будет выводить на экран сообщение о том, в какой координатной четверти лежит точка.
class Point {
public double x; // абсцисса точки
public double y; // ордината точки
// возвращает строку с описанием точки
public String toString() {
return "("+x+";"+y+")";
}
// выводит на экран описание точки
public void printPoint() {
System.out.print(this.toString());
}
// метод перемещает точку на указанный вектор
public void movePoint(double a, double b) {
x = x + a;
y = y + b;
}
// метод изменяет координаты точки на указанные
public void setPoint(double a, double b) {
x = a;
y = b;
}
// конструктор по умолчанию, создающий точку в начале координат
public Point() {
x = 0.0;
y = 0.0;
}
// конструктор, создающий точку с указанными координатами
public Point(double a, double b) {
x = a;
y = b;
}
// метод вычисляющий расстояние между точками
public double length(Point p) {
return Math.sqrt( Math.pow(p.x-x,2) + Math.pow(p.y-y,2) );
}
// метод проверяющий совпадают ли точки
public boolean equalsPoint(Point p) {
if(this.x == p.x && this.y == p.y) {
return true;
} else {
return false;
}
}
public void quarter() {
if(x>0&&y>0) {
System.out.println("Point p2 is in first coordinate quarter");
} else if(x<0&&y>0) {
System.out.println("Point p2 is in second coordinate quarter");
} else if(x<0&&y<0) {
System.out.println("Point p2 is in third coordinate quarter");
} else {
System.out.println("Point p2 is in fourth coordinate quarter");
}
}
}
public class one {
public static void main(String[] args) {
Point p1 = new Point();
Point p2 = new Point(-1,1);
System.out.println("Distanse between "+p1+" and "+p2+" equals "+p1.length(p2));
p2.quarter();
}
}
2. Задание
Создайте в классе метод, проверяющий, являются ли две точки симметричными относительно начала отсчёта.
import java.util.*;
class Point {
public double x; // абсцисса точки
public double y; // ордината точки
// возвращает строку с описанием точки
public String toString() {
return "("+x+";"+y+")";
}
// выводит на экран описание точки
public void printPoint() {
System.out.print(this.toString());
}
// метод перемещает точку на указанный вектор
public void movePoint(double a, double b) {
x = x + a;
y = y + b;
}
// метод изменяет координаты точки на указанные
public void setPoint(double a, double b) {
x = a;
y = b;
}
// конструктор по умолчанию, создающий точку в начале координат
public Point() {
x = 0.0;
y = 0.0;
}
// конструктор, создающий точку с указанными координатами
public Point(double a, double b) {
x = a;
y = b;
}
// метод вычисляющий расстояние между точками
public double length(Point p) {
return Math.sqrt( Math.pow(p.x-x,2) + Math.pow(p.y-y,2) );
}
// метод проверяющий совпадают ли точки
public boolean equalsPoint(Point p) {
if(this.x == p.x && this.y == p.y) {
return true;
} else {
return false;
}
}
public void quarter() {
if(x>0&&y>0) {
System.out.println("Point p2 is in first coordinate quarter");
} else if(x<0&&y>0) {
System.out.println("Point p2 is in second coordinate quarter");
} else if(x<0&&y<0) {
System.out.println("Point p2 is in third coordinate quarter");
} else {
System.out.println("Point p2 is in fourth coordinate quarter");
}
}
public void sim(Point p) {
if(Math.abs(this.x)==Math.abs(p.x)&&Math.abs(this.y)==Math.abs(p.y)) {
System.out.println("Points are symmetrical");
} else {
System.out.println("Points are not symmetrical");
}
}
}
public class two {
public static void main(String[] args) {
Point p1 = new Point(1,1);
Point p2 = new Point(-1,1);
System.out.println("Distanse between "+p1+" and "+p2+" equals "+p1.length(p2));
p2.quarter();
p1.sim(p2);
}
}
3. Задание
Измените в классе конструктор по умолчанию таким образом, чтобы начальные координаты точки при её создании пользователь задавал с клавиатуры.
import java.util.*;
class Point {
public double x; // абсцисса точки
public double y; // ордината точки
// возвращает строку с описанием точки
public String toString() {
return "("+x+";"+y+")";
}
// выводит на экран описание точки
public void printPoint() {
System.out.print(this.toString());
}
// метод перемещает точку на указанный вектор
public void movePoint(double a, double b) {
x = x + a;
y = y + b;
}
// метод изменяет координаты точки на указанные
public void setPoint(double a, double b) {
x = a;
y = b;
}
// конструктор по умолчанию, создающий точку в начале координат
public Point() {
System.out.println("Vvedite ordinatu tochki:");
Scanner sc1 = new Scanner(System.in);
if(sc1.hasNextInt()) {
x = sc1.nextInt();
}
System.out.println("Vvedite abstissu tochki:");
Scanner sc2 = new Scanner(System.in);
if(sc2.hasNextInt()) {
y = sc2.nextInt();
}
}
// конструктор, создающий точку с указанными координатами
public Point(double a, double b) {
x = a;
y = b;
}
// метод вычисляющий расстояние между точками
public double length(Point p) {
return Math.sqrt( Math.pow(p.x-x,2) + Math.pow(p.y-y,2) );
}
// метод проверяющий совпадают ли точки
public boolean equalsPoint(Point p) {
if(this.x == p.x && this.y == p.y) {
return true;
} else {
return false;
}
}
public void quarter() {
if(x>0&&y>0) {
System.out.println("Point p2 is in first coordinate quarter");
} else if(x<0&&y>0) {
System.out.println("Point p2 is in second coordinate quarter");
} else if(x<0&&y<0) {
System.out.println("Point p2 is in third coordinate quarter");
} else {
System.out.println("Point p2 is in fourth coordinate quarter");
}
}
public void sim(Point p) {
if(Math.abs(this.x)==Math.abs(p.x)&&Math.abs(this.y)==Math.abs(p.y)) {
System.out.println("Points are symmetrical");
} else {
System.out.println("Points are not symmetrical");
}
}
}
public class three {
public static void main(String[] args) {
Point p1 = new Point();
Point p2 = new Point(-1,1);
System.out.println("Distanse between "+p1+" and "+p2+" equals "+p1.length(p2));
p2.quarter();
p1.sim(p2);
}
}
4. Задание
Создайте в классе метод, проверяющий, являются ли три точки коллинеарными (т.е. лежащими на одной прямой).
import java.util.*;
class Point {
public double x; // абсцисса точки
public double y; // ордината точки
// возвращает строку с описанием точки
public String toString() {
return "("+x+";"+y+")";
}
// выводит на экран описание точки
public void printPoint() {
System.out.print(this.toString());
}
// метод перемещает точку на указанный вектор
public void movePoint(double a, double b) {
x = x + a;
y = y + b;
}
// метод изменяет координаты точки на указанные
public void setPoint(double a, double b) {
x = a;
y = b;
}
// конструктор по умолчанию, создающий точку в начале координат
public Point() {
System.out.println("Vvedite ordinatu tochki:");
Scanner sc1 = new Scanner(System.in);
if(sc1.hasNextInt()) {
x = sc1.nextInt();
}
System.out.println("Vvedite abstissu tochki:");
Scanner sc2 = new Scanner(System.in);
if(sc2.hasNextInt()) {
y = sc2.nextInt();
}
}
// конструктор, создающий точку с указанными координатами
public Point(double a, double b) {
x = a;
y = b;
}
// метод вычисляющий расстояние между точками
public double length(Point p) {
return Math.sqrt( Math.pow(p.x-x,2) + Math.pow(p.y-y,2) );
}
// метод проверяющий совпадают ли точки
public boolean equalsPoint(Point p) {
if(this.x == p.x && this.y == p.y) {
return true;
} else {
return false;
}
}
public void quarter() {
if(x>0&&y>0) {
System.out.println("Point p2 is in first coordinate quarter");
} else if(x<0&&y>0) {
System.out.println("Point p2 is in second coordinate quarter");
} else if(x<0&&y<0) {
System.out.println("Point p2 is in third coordinate quarter");
} else {
System.out.println("Point p2 is in fourth coordinate quarter");
}
}
public void sim(Point p) {
if(Math.abs(this.x)==Math.abs(p.x)&&Math.abs(this.y)==Math.abs(p.y)) {
System.out.println("Points are symmetrical");
} else {
System.out.println("Points are not symmetrical");
}
}
public void koll(Point p1, Point p2) {
double distx1 = this.x-p1.x;
double disty1 = this.y-p1.y;
double distx2 = p1.x-p2.x;
double disty2 = p1.y-p2.y;
double k1 = disty1/distx1;
double k2 = disty2/distx2;
double c1 = this.y-k1*this.x;
double c2 = p2.y-k2*p2.x;
if(k1==k2&&c1==c2) {
System.out.println("Kollinearni");
} else {
System.out.println("Ne kollinearni");
}
}
}
public class four {
public static void main(String[] args) {
Point p1 = new Point(1,1);
Point p2 = new Point(2,2);
Point p3 = new Point(3,3);
p1.printPoint();
System.out.println("Distanse between "+p1+" and "+p2+" equals "+p1.length(p2));
p2.quarter();
p1.sim(p2);
p1.koll(p2,p3);
}
}
5. Задание
Вместо представленного метода equalsPoint перегрузите в классе методы equals и hashCode.
import java.util.*;
class Point {
public double x; // абсцисса точки
public double y; // ордината точки
// возвращает строку с описанием точки
public String toString() {
return "("+x+";"+y+")";
}
// выводит на экран описание точки
public void printPoint() {
System.out.print(this.toString());
}
// метод перемещает точку на указанный вектор
public void movePoint(double a, double b) {
x = x + a;
y = y + b;
}
// метод изменяет координаты точки на указанные
public void setPoint(double a, double b) {
x = a;
y = b;
}
// конструктор по умолчанию, создающий точку в начале координат
public Point() {
System.out.println("Vvedite ordinatu tochki:");
Scanner sc1 = new Scanner(System.in);
if(sc1.hasNextDouble()) {
x = sc1.nextDouble();
}
System.out.println("Vvedite abstissu tochki:");
Scanner sc2 = new Scanner(System.in);
if(sc2.hasNextDouble()) {
y = sc2.nextDouble();
}
}
// конструктор, создающий точку с указанными координатами
public Point(double a, double b) {
x = a;
y = b;
}
// метод вычисляющий расстояние между точками
public double length(Point p) {
return Math.sqrt( Math.pow(p.x-x,2) + Math.pow(p.y-y,2) );
}
public int hashCode() {
double k = x*y;
return (int)k;
}
public boolean equals(Point p1) {
if(this.x==p1.x&&this.y==p1.y) {
return true;
} else {
return false;
}
}
public void quarter() {
if(x>0&&y>0) {
System.out.println("Point p2 is in first coordinate quarter");
} else if(x<0&&y>0) {
System.out.println("Point p2 is in second coordinate quarter");
} else if(x<0&&y<0) {
System.out.println("Point p2 is in third coordinate quarter");
} else {
System.out.println("Point p2 is in fourth coordinate quarter");
}
}
public void sim(Point p) {
if(Math.abs(this.x)==Math.abs(p.x)&&Math.abs(this.y)==Math.abs(p.y)) {
System.out.println("Points are symmetrical");
} else {
System.out.println("Points are not symmetrical");
}
}
public void koll(Point p1, Point p2) {
double distx1 = this.x-p1.x;
double disty1 = this.y-p1.y;
double distx2 = p1.x-p2.x;
double disty2 = p1.y-p2.y;
double k1 = disty1/distx1;
double k2 = disty2/distx2;
double c1 = this.y-k1*this.x;
double c2 = p2.y-k2*p2.x;
if(k1==k2&&c1==c2) {
System.out.println("Kollinearni");
} else {
System.out.println("Ne kollinearni");
}
}
}
public class five {
public static void main(String[] args) {
Point p1 = new Point(1.9,1.2);
Point p2 = new Point(1.9,1.2);
Point p3 = new Point(3,3);
p1.printPoint();
System.out.println("Distanse between "+p1+" and "+p2+" equals "+p1.length(p2));
p2.quarter();
p1.sim(p2);
p1.koll(p2,p3);
System.out.println(/*p1.equals(p2)*/p1.hashCode()+" "+p2.hashCode());
}
}
Создание классов (конец). Полиморфизм, инкапсуляция
1. Задание
Создайте класс треуголников на координатной плоскости, используя в качестве полей объекты-точки. Реализуйте в классе:
a) конструктор, позволяющий задавать вершины с клавиатуры;
b) метод print() выводящий описание треугольника на экран;
c) методы для вычисления периметра и площади треугольника.
import java.util.Scanner;
class Point {
public double x; // абсцисса точки
public double y; // ордината точки
// возвращает строку с описанием точки
public String toString() {
return "("+x+";"+y+")";
}
// выводит на экран описание точки
public void printPoint() {
System.out.print(this.toString());
}
// метод перемещает точку на указанный вектор
public void movePoint(double a, double b) {
x = x + a;
y = y + b;
}
// метод изменяет координаты точки на указанные
public void setPoint(double a, double b) {
x = a;
y = b;
}
// конструктор по умолчанию, создающий точку в начале координат
public Point() {
System.out.println("Vvedite ordinatu tochki:");
Scanner sc1 = new Scanner(System.in);
if(sc1.hasNextInt()) {
x = sc1.nextInt();
}
System.out.println("Vvedite abstissu tochki:");
Scanner sc2 = new Scanner(System.in);
if(sc2.hasNextInt()) {
y = sc2.nextInt();
}
}
// конструктор, создающий точку с указанными координатами
public Point(double a, double b) {
x = a;
y = b;
}
// метод вычисляющий расстояние между точками
public double length(Point p) {
return Math.sqrt( Math.pow(p.x-x,2) + Math.pow(p.y-y,2) );
}
// метод проверяющий совпадают ли точки
public boolean equalsPoint(Point p) {
if(this.x == p.x && this.y == p.y) {
return true;
} else {
return false;
}
}
public void quarter() {
if(x>0&&y>0) {
System.out.println("Point p2 is in first coordinate quarter");
} else if(x<0&&y>0) {
System.out.println("Point p2 is in second coordinate quarter");
} else if(x<0&&y<0) {
System.out.println("Point p2 is in third coordinate quarter");
} else {
System.out.println("Point p2 is in fourth coordinate quarter");
}
}
public void sim(Point p) {
if(Math.abs(this.x)==Math.abs(p.x)&&Math.abs(this.y)==Math.abs(p.y)) {
System.out.println("Points are symmetrical");
} else {
System.out.println("Points are not symmetrical");
}
}
public void koll(Point p1, Point p2) {
double distx1 = this.x-p1.x;
double disty1 = this.y-p1.y;
double distx2 = p1.x-p2.x;
double disty2 = p1.y-p2.y;
double k1 = disty1/distx1;
double k2 = disty2/distx2;
double c1 = this.y-k1*this.x;
double c2 = p2.y-k2*p2.x;
if(k1==k2&&c1==c2) {
System.out.println("Kollinearni");
} else {
System.out.println("Ne kollinearni");
}
}
}
class Triangle {
public Point A;
public Point B;
public Point C;
public Triangle() {
A = new Point();
B = new Point();
C = new Point();
}
public Triangle(double ax, double ay, double bx, double by, double cx, double cy) {
A = new Point(ax, ay);
B = new Point(bx, by);
C = new Point(cx, cy);
}
public String toString() {
return "Treygoljnik s koordinatami vershin: A="+A.toString()+"; B="+B.toString()+"; C="+C.toString()+";";
}
public void print() {
System.out.print(this.toString());
}
public double P() {
double a = Math.sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y));
double b = Math.sqrt((B.x-B.x)*(B.x-C.x)+(B.y-C.y)*(B.y-C.y));
double c = Math.sqrt((A.x-C.x)*(A.x-C.x)+(A.y-C.y)*(A.y-C.y));
System.out.println();
System.out.println(a);
System.out.println(b);
System.out.println(c);
return a+b+c;
}
public double S() {
double a = Math.sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y));
double b = Math.sqrt((B.x-B.x)*(B.x-C.x)+(B.y-C.y)*(B.y-C.y));
//double c = (A.x-C.x)*(A.x-C.x)+(A.y-C.y)*(A.y-C.y);
double h = Math.abs(a*a-b/2*b/2);
return h*b/2;
}
}
public class one {
public static void main(String[] args) {
Triangle abc = new Triangle(1,6,3,2,4,6);
abc.print();
System.out.println("Perimetr treygoljnika raven: "+abc.P());
System.out.println("Ploshad treygoljnika ravna: "+abc.S());
}
}
2. Задание
Доработайте конструктор таким образом, чтобы нельзя было задать три вершины, лежащие на одной прямой. Это несложно будет сделать с использованием метода из класса точек, который проверяет явлются ли точки коллинеарными, если прежде вы не реализовали этот метод, то сейчас самое время сделать это.
import java.util.Scanner;
class Point {
public double x; // абсцисса точки
public double y; // ордината точки
// возвращает строку с описанием точки
public String toString() {
return "("+x+";"+y+")";
}
// выводит на экран описание точки
public void printPoint() {
System.out.print(this.toString());
}
// метод перемещает точку на указанный вектор
public void movePoint(double a, double b) {
x = x + a;
y = y + b;
}
// метод изменяет координаты точки на указанные
public void setPoint(double a, double b) {
x = a;
y = b;
}
// конструктор по умолчанию, создающий точку в начале координат
public Point() {
System.out.println("Vvedite ordinatu tochki:");
Scanner sc1 = new Scanner(System.in);
if(sc1.hasNextInt()) {
x = sc1.nextInt();
}
System.out.println("Vvedite abstissu tochki:");
Scanner sc2 = new Scanner(System.in);
if(sc2.hasNextInt()) {
y = sc2.nextInt();
}
}
// конструктор, создающий точку с указанными координатами
public Point(double a, double b) {
x = a;
y = b;
}
// метод вычисляющий расстояние между точками
public double length(Point p) {
return Math.sqrt( Math.pow(p.x-x,2) + Math.pow(p.y-y,2) );
}
// метод проверяющий совпадают ли точки
public boolean equalsPoint(Point p) {
if(this.x == p.x && this.y == p.y) {
return true;
} else {
return false;
}
}
public void quarter() {
if(x>0&&y>0) {
System.out.println("Point p2 is in first coordinate quarter");
} else if(x<0&&y>0) {
System.out.println("Point p2 is in second coordinate quarter");
} else if(x<0&&y<0) {
System.out.println("Point p2 is in third coordinate quarter");
} else {
System.out.println("Point p2 is in fourth coordinate quarter");
}
}
public void sim(Point p) {
if(Math.abs(this.x)==Math.abs(p.x)&&Math.abs(this.y)==Math.abs(p.y)) {
System.out.println("Points are symmetrical");
} else {
System.out.println("Points are not symmetrical");
}
}
public boolean koll(Point p1, Point p2) {
double distx1 = this.x-p1.x;
double disty1 = this.y-p1.y;
double distx2 = p1.x-p2.x;
double disty2 = p1.y-p2.y;
double k1 = disty1/distx1;
double k2 = disty2/distx2;
double c1 = this.y-k1*this.x;
double c2 = p2.y-k2*p2.x;
if(k1==k2&&c1==c2) {
System.out.println("Kollinearni");
return true;
} else {
System.out.println("Ne kollinearni");
return false;
}
}
}
class Triangle {
public Point A;
public Point B;
public Point C;
public Triangle() {
Point a = new Point();
Point b = new Point();
Point c = new Point();
if(!a.koll(b,c)) {
A = new Point(a.x, a.y);
B = new Point(b.x, b.y);
C = new Point(c.x, c.y);
} else {
System.out.println("Tochki, zadannije vami, yavljyajytsa kollinearnimi, treugoljnik postroit nevozmojno");
A = new Point(-1, 0);
B = new Point(0, 1);
C = new Point(1, 1);
}
}
public Triangle(double ax, double ay, double bx, double by, double cx, double cy) {
Point a = new Point(ax, ay);
Point b = new Point(bx, by);
Point c = new Point(cx, cy);
if(!a.koll(b,c)) {
A = new Point(ax, ay);
B = new Point(bx, by);
C = new Point(cx, cy);
} else {
System.out.println("Tochki, zadannije vami, yavljyajytsa kollinearnimi, treugoljnik postroit nevozmojno");
A = new Point(-1, 0);
B = new Point(0, 1);
C = new Point(1, 1);
}
}
public String toString() {
return "Treygoljnik s koordinatami vershin: A="+A.toString()+"; B="+B.toString()+"; C="+C.toString()+";";
}
public void print() {
System.out.print(this.toString());
}
public double P() {
double a = Math.sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y));
double b = Math.sqrt((B.x-B.x)*(B.x-C.x)+(B.y-C.y)*(B.y-C.y));
double c = Math.sqrt((A.x-C.x)*(A.x-C.x)+(A.y-C.y)*(A.y-C.y));
System.out.println();
System.out.println(a);
System.out.println(b);
System.out.println(c);
return a+b+c;
}
public double S() {
double a = Math.sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y));
double b = Math.sqrt((B.x-B.x)*(B.x-C.x)+(B.y-C.y)*(B.y-C.y));
//double c = (A.x-C.x)*(A.x-C.x)+(A.y-C.y)*(A.y-C.y);
double h = Math.abs(a*a-b/2*b/2);
return h*b/2;
}
}
public class two {
public static void main(String[] args) {
//Triangle abc = new Triangle(1,6,3,2,4,6);
//Triangle abc = new Triangle(1,1,2,2,3,3);
Triangle abc = new Triangle();
abc.print();
System.out.println("Perimetr treygoljnika raven: "+abc.P());
System.out.println("Ploshad treygoljnika ravna: "+abc.S());
}
}
3. Задание
Инкапсулируйте поля таким образом, чтобы нельзя изменить значение любого из них так, чтобы вершины оказались на одной прямой.
import java.util.Scanner;
class Point {
public double x; // абсцисса точки
public double y; // ордината точки
// возвращает строку с описанием точки
public String toString() {
return "("+x+";"+y+")";
}
// выводит на экран описание точки
public void printPoint() {
System.out.print(this.toString());
}
// метод перемещает точку на указанный вектор
public void movePoint(double a, double b) {
x = x + a;
y = y + b;
}
// метод изменяет координаты точки на указанные
public void setPoint(double a, double b) {
x = a;
y = b;
}
// конструктор по умолчанию, создающий точку в начале координат
public Point() {
System.out.println("Vvedite ordinatu tochki:");
Scanner sc1 = new Scanner(System.in);
if(sc1.hasNextInt()) {
x = sc1.nextInt();
}
System.out.println("Vvedite abstissu tochki:");
Scanner sc2 = new Scanner(System.in);
if(sc2.hasNextInt()) {
y = sc2.nextInt();
}
}
// конструктор, создающий точку с указанными координатами
public Point(double a, double b) {
x = a;
y = b;
}
// метод вычисляющий расстояние между точками
public double length(Point p) {
return Math.sqrt( Math.pow(p.x-x,2) + Math.pow(p.y-y,2) );
}
// метод проверяющий совпадают ли точки
public boolean equalsPoint(Point p) {
if(this.x == p.x && this.y == p.y) {
return true;
} else {
return false;
}
}
public void quarter() {
if(x>0&&y>0) {
System.out.println("Point p2 is in first coordinate quarter");
} else if(x<0&&y>0) {
System.out.println("Point p2 is in second coordinate quarter");
} else if(x<0&&y<0) {
System.out.println("Point p2 is in third coordinate quarter");
} else {
System.out.println("Point p2 is in fourth coordinate quarter");
}
}
public void sim(Point p) {
if(Math.abs(this.x)==Math.abs(p.x)&&Math.abs(this.y)==Math.abs(p.y)) {
System.out.println("Points are symmetrical");
} else {
System.out.println("Points are not symmetrical");
}
}
public boolean koll(Point p1, Point p2) {
double distx1 = this.x-p1.x;
double disty1 = this.y-p1.y;
double distx2 = p1.x-p2.x;
double disty2 = p1.y-p2.y;
double k1 = disty1/distx1;
double k2 = disty2/distx2;
double c1 = this.y-k1*this.x;
double c2 = p2.y-k2*p2.x;
if(k1==k2&&c1==c2) {
System.out.println("Kollinearni");
return true;
} else {
System.out.println("Ne kollinearni");
return false;
}
}
}
class Triangle {
private Point A;
private Point B;
private Point C;
public Triangle() {
Point a = new Point();
Point b = new Point();
Point c = new Point();
if(!a.koll(b,c)) {
A = new Point(a.x, a.y);
B = new Point(b.x, b.y);
C = new Point(c.x, c.y);
} else {
System.out.println("Tochki, zadannije vami, yavljyajytsa kollinearnimi, treugoljnik postroit nevozmojno");
A = new Point(-1, 0);
B = new Point(0, 1);
C = new Point(1, 1);
}
}
public Triangle(double ax, double ay, double bx, double by, double cx, double cy) {
Point a = new Point(ax, ay);
Point b = new Point(bx, by);
Point c = new Point(cx, cy);
if(!a.koll(b,c)) {
A = new Point(ax, ay);
B = new Point(bx, by);
C = new Point(cx, cy);
} else {
System.out.println("Tochki, zadannije vami, yavljyajytsa kollinearnimi, treugoljnik postroit nevozmojno");
A = new Point(-1, 0);
B = new Point(0, 1);
C = new Point(1, 1);
}
}
public String toString() {
return "Treygoljnik s koordinatami vershin: A="+A.toString()+"; B="+B.toString()+"; C="+C.toString()+";";
}
public void print() {
System.out.print(this.toString());
}
public double P() {
double a = Math.sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y));
double b = Math.sqrt((B.x-B.x)*(B.x-C.x)+(B.y-C.y)*(B.y-C.y));
double c = Math.sqrt((A.x-C.x)*(A.x-C.x)+(A.y-C.y)*(A.y-C.y));
System.out.println();
System.out.println(a);
System.out.println(b);
System.out.println(c);
return a+b+c;
}
public double S() {
double a = Math.sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y));
double b = Math.sqrt((B.x-B.x)*(B.x-C.x)+(B.y-C.y)*(B.y-C.y));
//double c = (A.x-C.x)*(A.x-C.x)+(A.y-C.y)*(A.y-C.y);
double h = Math.abs(a*a-b/2*b/2);
return h*b/2;
}
public Point getA() {
return A;
}
public Point getB() {
return B;
}
public Point getC() {
return C;
}
public void setA(double x, double y) {
Point p = new Point(x,y);
if(!p.koll(B,C)) {
A = p;
} else {
System.out.println("Tochku pomenjat neljza, t. k. ona budet kollinearna k drugim vershinam treugolnika");
}
}
public void setB(double x, double y) {
Point p = new Point(x,y);
if(!p.koll(A,C)) {
B = p;
} else {
System.out.println("Tochku pomenjat neljza, t. k. ona budet kollinearna k drugim vershinam treugolnika");
}
}
public void setC(double x, double y) {
Point p = new Point(x,y);
if(!p.koll(A,B)) {
C = p;
} else {
System.out.println("Tochku pomenjat neljza, t. k. ona budet kollinearna k drugim vershinam treugolnika");
}
}
}
public class three {
public static void main(String[] args) {
Triangle abc = new Triangle(1,6,3,2,4,6);
//Triangle abc = new Triangle(1,1,2,2,3,3);
//Triangle abc = new Triangle();
abc.print();
System.out.println("Perimetr treygoljnika raven: "+abc.P());
System.out.println("Ploshad treygoljnika ravna: "+abc.S());
abc.setA(10,11);
abc.print();
}
}
4. Задание
Создайте метод, поворачивающий треугольник вокруг центра тяжести на указанное в аргументе количество градусов.
import java.util.Scanner;
class Point {
public double x; // абсцисса точки
public double y; // ордината точки
// возвращает строку с описанием точки
public String toString() {
return "("+x+";"+y+")";
}
// выводит на экран описание точки
public void printPoint() {
System.out.print(this.toString());
}
// метод перемещает точку на указанный вектор
public void movePoint(double a, double b) {
x = x + a;
y = y + b;
}
// метод изменяет координаты точки на указанные
public void setPoint(double a, double b) {
x = a;
y = b;
}
// конструктор по умолчанию, создающий точку в начале координат
public Point() {
System.out.println("Vvedite ordinatu tochki:");
Scanner sc1 = new Scanner(System.in);
if(sc1.hasNextInt()) {
x = sc1.nextInt();
}
System.out.println("Vvedite abstissu tochki:");
Scanner sc2 = new Scanner(System.in);
if(sc2.hasNextInt()) {
y = sc2.nextInt();
}
}
// конструктор, создающий точку с указанными координатами
public Point(double a, double b) {
x = a;
y = b;
}
// метод вычисляющий расстояние между точками
public double length(Point p) {
return Math.sqrt( Math.pow(p.x-x,2) + Math.pow(p.y-y,2) );
}
// метод проверяющий совпадают ли точки
public boolean equalsPoint(Point p) {
if(this.x == p.x && this.y == p.y) {
return true;
} else {
return false;
}
}
public void quarter() {
if(x>0&&y>0) {
System.out.println("Point p2 is in first coordinate quarter");
} else if(x<0&&y>0) {
System.out.println("Point p2 is in second coordinate quarter");
} else if(x<0&&y<0) {
System.out.println("Point p2 is in third coordinate quarter");
} else {
System.out.println("Point p2 is in fourth coordinate quarter");
}
}
public void sim(Point p) {
if(Math.abs(this.x)==Math.abs(p.x)&&Math.abs(this.y)==Math.abs(p.y)) {
System.out.println("Points are symmetrical");
} else {
System.out.println("Points are not symmetrical");
}
}
public boolean koll(Point p1, Point p2) {
double distx1 = this.x-p1.x;
double disty1 = this.y-p1.y;
double distx2 = p1.x-p2.x;
double disty2 = p1.y-p2.y;
double k1 = disty1/distx1;
double k2 = disty2/distx2;
double c1 = this.y-k1*this.x;
double c2 = p2.y-k2*p2.x;
if(k1==k2&&c1==c2) {
System.out.println("Kollinearni");
return true;
} else {
System.out.println("Ne kollinearni");
return false;
}
}
}
class Triangle {
private Point A;
private Point B;
private Point C;
public Triangle() {
Point a = new Point();
Point b = new Point();
Point c = new Point();
if(!a.koll(b,c)) {
A = new Point(a.x, a.y);
B = new Point(b.x, b.y);
C = new Point(c.x, c.y);
} else {
System.out.println("Tochki, zadannije vami, yavljyajytsa kollinearnimi, treugoljnik postroit nevozmojno");
A = new Point(-1, 0);
B = new Point(0, 1);
C = new Point(1, 1);
}
}
public Triangle(double ax, double ay, double bx, double by, double cx, double cy) {
Point a = new Point(ax, ay);
Point b = new Point(bx, by);
Point c = new Point(cx, cy);
if(!a.koll(b,c)) {
A = new Point(ax, ay);
B = new Point(bx, by);
C = new Point(cx, cy);
} else {
System.out.println("Tochki, zadannije vami, yavljyajytsa kollinearnimi, treugoljnik postroit nevozmojno");
A = new Point(-1, 0);
B = new Point(0, 1);
C = new Point(1, 1);
}
}
public String toString() {
return "Treygoljnik s koordinatami vershin: A="+A.toString()+"; B="+B.toString()+"; C="+C.toString()+";";
}
public void print() {
System.out.print(this.toString());
}
public double P() {
double a = Math.sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y));
double b = Math.sqrt((B.x-B.x)*(B.x-C.x)+(B.y-C.y)*(B.y-C.y));
double c = Math.sqrt((A.x-C.x)*(A.x-C.x)+(A.y-C.y)*(A.y-C.y));
/*System.out.println();
System.out.println(a);
System.out.println(b);
System.out.println(c);*/
return a+b+c;
}
public double S() {
double a = Math.sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y));
double b = Math.sqrt((B.x-B.x)*(B.x-C.x)+(B.y-C.y)*(B.y-C.y));
//double c = (A.x-C.x)*(A.x-C.x)+(A.y-C.y)*(A.y-C.y);
double h = Math.abs(a*a-b/2*b/2);
return h*b/2;
}
public Point getA() {
return A;
}
public Point getB() {
return B;
}
public Point getC() {
return C;
}
public void setA(double x, double y) {
Point p = new Point(x,y);
if(!p.koll(B,C)) {
A = p;
} else {
System.out.println("Tochku pomenjat neljza, t. k. ona budet kollinearna k drugim vershinam treugolnika");
}
}
public void setB(double x, double y) {
Point p = new Point(x,y);
if(!p.koll(A,C)) {
B = p;
} else {
System.out.println("Tochku pomenjat neljza, t. k. ona budet kollinearna k drugim vershinam treugolnika");
}
}
public void setC(double x, double y) {
Point p = new Point(x,y);
if(!p.koll(A,B)) {
C = p;
} else {
System.out.println("Tochku pomenjat neljza, t. k. ona budet kollinearna k drugim vershinam treugolnika");
}
}
public void rotate(double deg) {
double rad,cos,sin;
if(deg == 90) {
cos = 0;
sin = 1;
} else {
rad = deg*Math.PI/180;
cos = Math.cos(rad);
sin = Math.sin(rad);
}
double newAx = A.x*cos-A.y*sin;
double newAy = A.x*sin-A.y*cos;
double newBx = B.x*cos-B.y*sin;
double newBy = B.x*sin-B.y*cos;
double newCx = C.x*cos-C.y*sin;
double newCy = C.x*sin-C.y*cos;
A.x = newAx;
A.y = newAy;
B.x = newBx;
B.y = newBy;
C.x = newCx;
C.y = newCy;
/*A.x = A.x*Math.cos(rad)-A.y*Math.sin(rad);
A.y = A.x*Math.sin(rad)-A.y*Math.cos(rad);
B.x = B.x*Math.cos(rad)-B.y*Math.sin(rad);
B.y = B.x*Math.sin(rad)-B.y*Math.cos(rad);
C.x = C.x*Math.cos(rad)-C.y*Math.sin(rad);
C.y = C.x*Math.sin(rad)-C.y*Math.cos(rad);*/
//Triangle tr = new Triangle(A,B,C);
//return tr;
}
}
public class four {
public static void main(String[] args) {
//Triangle abc = new Triangle(1,6,3,2,4,6);
//Triangle abc = new Triangle(1,1,2,2,3,3);
Triangle abc = new Triangle(-1,0,0,1,1,0);
abc.print();
System.out.println("Perimetr treygoljnika raven: "+abc.P());
System.out.println("Ploshad treygoljnika ravna: "+abc.S());
//abc.setA(10,11);
//abc.print();
System.out.println();
System.out.println(Math.sin(Math.PI));
abc.rotate(45);
System.out.println("Rotate 45");
abc.print();
}
}
|
|