Главная » Статьи » JavaRush

JavaRush - классы и обьекты - level 05
package com.javarush.test.level05.lesson05.task01;

/* Создать класс Cat
Создать класс Cat. У кота должно быть имя (name, String),
 возраст (age, int), вес (weight, int), сила (strength, int).
*/

public class Cat
{
 String name;
 int age;
 int weight;
 int strength;//напишите тут ваш код

}

#############################################################

package com.javarush.test.level05.lesson05.task02;

/* Реализовать метод fight
Реализовать метод boolean fight(Cat anotherCat):
реализовать механизм драки котов в зависимости от их веса, возраста и силы.
Зависимость придумать самому. Метод должен определять, выиграли ли мы (this) бой или нет,
т.е. возвращать true, если выиграли и false - если нет.
Должно выполняться условие:
если cat1.fight(cat2) = true , то cat2.fight(cat1) = false
*/

public class Cat
{
 public String name;
 public int age;
 public int weight;
 public int strength;

 public static void main(String[] args)
 {

 Cat tom = new Cat();
 tom.name = "Tom";
 tom.weight = 25;
 tom.strength = 15;
 tom.age = 3;

 Cat fil = new Cat();
 fil.name = "Fil";
 fil.age = 1;
 fil.strength = 20;
 fil.weight = 20;

 //fil.fight(tom);
if(fil.fight(tom))
 System.out.print("Tom - proigral");
else
 System.out.print("Fil - proigral");
 }
 public Cat()
 {
 this.name = name;
 this.age = age;
 this.weight = weight;
 this.strength = strength;
 }

 public boolean fight(Cat anotherCat)
 {
 if(this.strength > anotherCat.strength)
 {
 return true;
 }
 else return false; //напишите тут ваш код

 }
}

########################################################################

package com.javarush.test.level05.lesson05.task03;

/* Геттеры и сеттеры для класса Dog
Создать class Dog. У собаки должна быть кличка String name и 
возраст int age.
Создайте геттеры и сеттеры для всех переменных класса Dog.
*/

public class Dog {
 public String name;
 public int age;//добавьте переменные класса тут

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

 public int getAge(){
 return age;
 }
 public void setAge(int age){
 this.age = age;
 }

}

#######################################################################

package com.javarush.test.level05.lesson05.task04;

/* Создать три объекта типа Cat
В методе main создать три объекта типа Cat и заполнить их данными.
Использовать класс Cat из первой задачи. Класс Cat создавать не надо.
*/

public class Solution {
 public static void main(String[] args) {
 Cat cat1 = new Cat("cat1", 5, 4, 6);
 Cat cat2 = new Cat("cat2", 4, 3, 7);
 Cat cat3 = new Cat("cat3", 3, 2, 8);
 }

 public static class Cat {

 public static int count = 0;
 private String name;
 private int age;
 private int weight;
 private int strength;

 public Cat(String name, int age, int weight, int strength) {
 count++;

 this.name = name;
 this.age = age;
 this.weight = weight;
 this.strength = strength;
 }
 }
}

##################################################################

package com.javarush.test.level05.lesson05.task05;

/* Провести три боя попарно между котами
Создать три кота используя класс Cat.
Провести три боя попарно между котами.
Класс Cat создавать не надо. Для боя использовать метод 
boolean fight(Cat anotherCat).
Результат каждого боя вывести на экран.
*/

public class Solution {
 public static void main(String[] args) {
 Cat cat1 = new Cat("Cat1", 5, 8, 30);
 Cat cat2 = new Cat("Cat2", 3, 5, 20);
 Cat cat3 = new Cat("Cat3", 4, 7, 30);

 System.out.println(cat1.fight(cat2));
 System.out.println(cat2.fight(cat3));
 System.out.println(cat3.fight(cat1));//напишите тут ваш код
 }

 public static class Cat {

 public static int count = 0;
 public static int fightCount = 0;

 protected String name;
 protected int age;
 protected int weight;
 protected int strength;

 public Cat(String name, int age, int weight, int strength) {
 count++;

 this.name = name;
 this.age = age;
 this.weight = weight;
 this.strength = strength;
 }

 public boolean fight(Cat anotherCat) {
 fightCount++;

 int agePlus = this.age > anotherCat.age ? 1 : 0;
 int weightPlus = this.weight > anotherCat.weight ? 1 : 0;
 int strengthPlus = this.strength > anotherCat.strength ? 1 : 0;

 int score = agePlus + weightPlus + strengthPlus;
 return score > 2; // return score > 2 ? true : false;
 }
 }
}

################################################################################

package com.javarush.test.level05.lesson07.task01;

/* Создать класс Friend
Создать класс Friend (друг) с тремя инициализаторами (тремя методами initialize):
- Имя
- Имя, возраст
- Имя, возраст, пол
*/

public class Friend
{
 private String name;
 private int age;
 private String gender;

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

 public void initialize( String name, int age )
 {
 this.name = name;
 this.age = age;
 }

 public void initialize( String name, int age, String gender )
 {
 this.name = name;
 this.age = age;
 this.gender = gender;
 }
}

#############################################################

javarush.test.level05.lesson07.task03;

/* Создать класс Dog
Создать класс Dog (собака) с тремя инициализаторами:
- Имя
- Имя, рост
- Имя, рост, цвет
*/

public class Dog
{
 private String name;
 private int height;
 private String color;

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

 public void initialize(String name, int height){
 this.name=name;
 this.height=height;
 }

 public void initialize(String name, int height, String color){
 this.name = name;
 this.height=height;
 this.color=color;
 }

}

##############################################################

package com.javarush.test.level05.lesson07.task04;

/* Создать класс Circle
Создать класс (Circle) круг, с тремя инициализаторами:
- centerX, centerY, radius
- centerX, centerY, radius, width
- centerX, centerY, radius, width, color
*/

public class Circle
{
 private int centerX;
 private int centerY;
 private int radius;
 private int width;
 private String color;

 public void initialize(int centerX, int centerY, int radius){
 this.centerX = centerX;
 this.centerY = centerY;
 this.radius = radius;
 }
 public void initialize(int centerX, int centerY, int radius, int width){
 this.centerX = centerX;
 this.centerY = centerY;
 this.radius = radius;
 this.width = width;
 }
 public void initialize(int centerX, int centerY, int radius, int width, String color){
 this.centerX = centerX;
 this.centerY = centerY;
 this.radius = radius;
 this.width = width;
 this.color = color;
 }
}

######################################################################

 

package com.javarush.test.level05.lesson07.task02;

/* Создать класс Cat
Создать класс Cat (кот) с пятью инициализаторами:
- Имя,
- Имя, вес, возраст
- Имя, возраст (вес стандартный)
- вес, цвет, (имя, адрес и возраст неизвестны, это бездомный кот)
- вес, цвет, адрес ( чужой домашний кот)
Задача инициализатора – сделать объект валидным. Например,
 если вес неизвестен, то нужно указать какой-нибудь средний вес. 
Кот не может ничего не весить. То же касательно возраста. 
А вот имени может и не быть (null). То же касается адреса: null.
Тот параметр который не передан в аргументах нужно определить в методе.
*/

public class Cat
{
 private String name;
 private int age;
 private String address;
 private String color;
 private int weight;

 public void initialize( String name )
 {
 this.name = name;
 this.age = 1;
 this.weight = 4;
 }

 public void initialize( String name, int weight, int age )
 {
 this.name = name;
 this.weight = weight;
 this.age = age;
 }

 public void initialize( String name, int age )
 {
 this.name = name;
 this.age = age;
 this.weight = 3;
 }

 public void initialize( int weight, String color )
 {
 this.weight = weight;
 this.color = color;
 this.age =1;
 }

 public void initialize( int weight, String color, String address )
 {
 this.weight = weight;
 this.color = color;
 this.address = address;
 this.age = 1;
 }
}

###################################################################

package com.javarush.test.level05.lesson07.task05;

/* Создать класс прямоугольник (Rectangle)
Создать класс прямоугольник (Rectangle). 
Его данными будут top, left, width, height (левая координата, 
верхняя, ширина и высота). Создать для него
 как можно больше методов initialize(…)
Примеры:
- заданы 4 параметра: left, top, width, height
- ширина/высота не задана (оба равны 0)
- высота не задана (равно ширине) создаём квадрат
- создаём копию другого прямоугольника (он и передаётся в параметрах)
*/

public class Rectangle
{
 private int top;
 private int left;
 private int width;
 private int height;

 public void initialize( int left, int top, int width, int height )
 {
 this.left = left;
 this.top = top;
 this.width = width;
 this.height = height;
 }

 public void initialize( int left, int top )
 {
 this.left = left;
 this.top = top;
 this.width = 0;
 this.height = 0;
 }

 public void initialize( int left, int top, int width )
 {
 this.left = left;
 this.top = top;
 this.width = width;
 this.height = width;
 }

 public void initialize( Rectangle rectangle )
 {
 this.left = rectangle.left;
 this.top = rectangle.top;
 this.width = rectangle.width;
 this.height = rectangle.height;
 }
}

###############################################################

Конструкторы

package com.javarush.test.level05.lesson09.task01;

/* Создать класс Friend
Создать класс Friend (друг) с тремя конструкторами:
- Имя
- Имя, возраст
- Имя, возраст, пол
*/

public class Friend
{
 private String name;
 private int age;
 private Boolean sex;

 public Friend (String name){
 this.name = name;
 }

 public Friend (String name, int age){
 this.name=name;
 this.age=age;
 }

 public Friend (String name, int age, Boolean sex){
 this.name=name;
 this.age=age;
 this.sex=sex;
 }
}

#####################################################################

package com.javarush.test.level05.lesson09.task03;

/* Создать класс Dog
Создать класс Dog (собака) с тремя конструкторами:
- Имя
- Имя, рост
- Имя, рост, цвет
*/

public class Dog
{
 private String name;
 private int height;
 private String color;

 public Dog(String name){
 this.name=name;
 }

 public Dog(String name, int height){
 this.name=name;
 this.height=height;
 }

 public Dog(String name, int height, String color){
 this.name=name;
 this.height=height;
 this.color=color;
 }

}

########################################################

package com.javarush.test.level05.lesson09.task04;

/* Создать класс Circle
Создать класс (Circle) круг, с тремя конструкторами:
- centerX, centerY, radius
- centerX, centerY, radius, width
- centerX, centerY, radius, width, color
*/

public class Circle
{

 private String centerX;
 private String centerY;
 private int radius;
 private int width;
 private String color;


 public Circle(String centerX, String centerY, int radius){
 this.centerX=centerX;
 this.centerY=centerY;
 this.radius=radius;
 }

 public Circle(String centerX, String centerY, int radius, int width){
 this.centerX=centerX;
 this.centerY=centerY;
 this.radius=radius;
 this.width=width;
 }

 public Circle(String centerX, String centerY, int radius, int width, String color){
 this.centerX=centerX;
 this.centerY=centerY;
 this.radius=radius;
 this.width=width;
 this.color=color;
 }
}

##############################################################

package com.javarush.test.level05.lesson09.task05;

/* Создать класс прямоугольник (Rectangle)
Создать класс прямоугольник (Rectangle). Его данными будут top, left, width, height (левая координата, верхняя, ширина и высота). Создать для него как можно больше конструкторов:
Примеры:
- заданы 4 параметра: left, top, width, height
- ширина/высота не задана (оба равны 0)
- высота не задана (равно ширине) создаём квадрат
- создаём копию другого прямоугольника (он и передаётся в параметрах)
*/

public class Rectangle
{
 private int top;
 private int left;
 private int width;
 private int height;

 Rectangle(int left, int top, int width, int height){
 this.left = left;
 this.top = top;
 this.width = width;
 this.height = height;
 }

 Rectangle(int left, int top){
 this.left = left;
 this.top = top;
 this.width = 0;
 this.height = 0;
 }
 Rectangle(int left, int top, int width){
 this.left = left;
 this.top = top;
 this.width = width;
 this.height = width;
 }
 public Rectangle(Rectangle rectangle) {// делаем копию другого прямоугольника
 this.left = rectangle.left;
 this.top = rectangle.top;
 this.width = rectangle.width;
 this.height = rectangle.height;
 }


}

######################################################

package com.javarush.test.level05.lesson12.home02;

/* Man and Woman
1. Внутри класса Solution создай public static классы Man и Woman.
2. У классов должны быть поля: name(String), age(int), address(String).
3. Создай конструкторы, в которые передаются все возможные параметры.
4. Создай по два объекта каждого класса со всеми данными используя конструктор.
5. Объекты выведи на экран в таком формате [name + " " + age + " " + address].
*/

public class Solution
{
 public static void main(String[] args)
 {
 Man vasa = new Man("Вася", 19, "Москва");
 Man peta = new Man("Петя", 23, "Берлин");
 Woman tana = new Woman("Таня", 18, "Женева");
 Woman mana = new Woman("Маня", 19, "Киев");


 System.out.println(vasa);
 System.out.println(peta);
 System.out.println(tana);
 System.out.println(mana);
 }

 public static class Man {
 String name;
 int age;
 String address;

 public Man(String name, int age, String address) {
 this.name = name;
 this.age = age;
 this.address = address;
 }

 public String toString() {
 return name + " " + age + " " + address;
 }
 }

 public static class Woman {
 String name;
 int age;
 String address;

 public Woman(String name, int age, String address) {
 this.name = name;
 this.age = age;
 this.address = address;
 }

 public String toString() {
 return name + " " + age + " " + address;
 }
 }
}

###########################################################

package com.javarush.test.level05.lesson12.home03;

/* Создай классы Dog, Cat, Mouse
Создай классы Dog, Cat, Mouse. Добавь по три поля в каждый класс, на твой выбор. Создай объекты для героев мультика Том и Джерри. Так много, как только вспомнишь.
Пример:
Mouse jerryMouse = new Mouse(“Jerry”, 12 , 5), где 12 - высота в см, 5 - длина хвоста в см.
*/

public class Solution
{
 public static void main(String[] args)
 {
 Mouse jerryMouse = new Mouse("Jerry", 12 , 5);

 Cat catTom = new Cat("Tom", 30, 10);
 Dog dogFox = new Dog("Fox", 50, 20);
 }

 public static class Mouse
 {
 String name;
 int height;
 int tail;

 public Mouse(String name, int height, int tail)
 {
 this.name = name;
 this.height = height;
 this.tail = tail;
 }
 }

 public static class Cat
 {
 String name;
 int height;
 int tail;

 public Cat(String name, int height, int tail)
 {
 this.name = name;
 this.height = height;
 this.tail = tail;
 }
 }
 public static class Dog
 {
 String name;
 int height;
 int tail;

 public Dog(String name, int height, int tail)
 {
 this.name = name;
 this.height = height;
 this.tail = tail;
 }
 }

}

########################################################

 

 

 

 

Категория: JavaRush | Добавил: kuzma (24.01.2017)
Просмотров: 2530 | Рейтинг: 2.0/1
Всего комментариев: 0
avatar

Программирование игр на Python

Django - создание сайтов с нуля

Javascript - просто используем готовые решения