Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

Dimov79 avatar Dimov79 6 Точки

Ex3 Animal Farm from Encapsulation - Exercises

 

Здравейте, 

опитвам различни варианти, но получавам 90/100. Благодаря предварително за съдействието. 

https://www.mediafire.com/file/xyzy1m8doton5vw/animalFarm.zip/file

https://judge.softuni.bg/Contests/Compete/Index/1536#1

  1. Animal Farm

You should be familiar with encapsulation already. For this problem, you’ll need to create class called Chicken. Chicken should contain several fields, a constructor, and several methods. Your task is to encapsulate or hide anything that is not intended to be viewed or modified from outside the class.


 

Chicken

-

name: String

-

age: int

+

Chicken(String, int)

-

setName(String) : void

-

setAge (int): void

+

productPerDay (): double

+

toString(): Override

-

calculateProductPerDay() : double


 

Chicken lives for 15 years. Chicken have name for sure, at least 1 symbol long. Chicken producing eggs:

  • First 6 years it produces 2 eggs per day [0 - 5]

  • Next 6 years it produces 1 egg per day [6 - 11]

  • And after that it produces 0.75 eggs per day

Step 1. Encapsulate Fields

Fields should be private. Leaving fields open for modification from outside the class is potentially dangerous. Make all fields in the Chicken class private.

In case the value inside a field is needed elsewhere, use getters to reveal it.

Step 2. Ensure Classes Have a Correct State

Having getters and setters is useless if you don’t actually use them. The Chicken constructor modifies the fields directly which is wrong when there are suitable setters available. Modify the constructor to fix this issue.

Step 3. Validate Data Properly

Validate the chicken’s name (it cannot be null, empty or whitespace). In case of invalid name, print exception message "Name cannot be empty."

Validate the age properly, minimum and maximum age are provided, make use of them. In case of invalid age, print exception message "Age should be between 0 and 15."

Step 4. Hide Internal Logic

If a method is intended to be used only by descendant classes or internally to perform some action, there is no point in keeping them public. The calculateProductPerDay() method is used by the productPerDay() public method. This means the method can safely be hidden inside the Chicken class by declaring it private.

Step 4. Submit Code to Judge

Submit your code as a zip file in Judge. Make sure you have a public Main class with a public static void main method in it.

Examples

Input

Output

Mara

10

Chicken Mara (age 10) can produce 1.00 eggs per day.

Mara

17

Age should be between 0 and 15.

Gosho

6

Chicken Gosho (age 6) can produce 1.00 eggs per day.


 

Тагове:
0
Java OOP Advanced
RadostinD avatar RadostinD 16 Точки

Здравей,

Две неща ми правят впечатление в кода ти.

Първото, в конструктора си направо записваш данните, но не ги проверяваш. Може да го направиш така:

public Chicken(String name, int age) {
    this.setName(name);
    this.setAge(age);
}

Така ще може всичко идващо да мине през проверката дали е валидно, а не да бъде директно записвано.

 

Второ, в метода ти calculateProductPerDay проверяваш дали е до 15(невключително), а трябва да е <= 15. Не е нужно да правиш сложни проверки в този метод, защото вече имаш проверка дали годините са валидни.

Може да го направиш така:

private double calculateProductPerDay () {
    double eggsPerDay = 0;
    if (this.age <=5) {
        eggsPerDay = 2;
    } else if (this.age <= 11) {
        eggsPerDay = 1;
    } else if (this.age <= 15) {
        eggsPerDay = 0.75;
    }
    return eggsPerDay;

}

 

Поздрави,

Радо

0
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.