лаба 2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

Санкт-Петербургский политехнический университет Петра Великого

Институт компьютерных наук и технологий


Высшая школа киберфизических систем и управления

ЛАБОРАТОРНАЯ РАБОТА №2
по дисциплине «Курсы Java Foundations и Java Programming»

Выполнил
студент
гр. 3530902/70201 _____________________ Медведева А.А.
подпись, дата

Проверил
_____________________ Нестеров С.А.
подпись, дата

Санкт-Петербург
2020
Выполнение задания
Задание 1
Результаты работы программы:
Код программы:
#AnimalTester
package animalshop;

public class AnimalTester {

public static void main(String[] args) {


// TODO Auto-generated method stub
Dog dog = new Dog("Bailey", "Boerboel", "arf-arf", 80.2, "brown");
Fish fish = new Fish("Goldfish", "cold", "red");

System.out.println("Dog name : " + dog.getName());


System.out.println("Dog breed : " + dog.getBreed());
System.out.print("Bark noise: "); dog.bark();
System.out.println("Dog weight: " + dog.getWeight());
System.out.println("Dog colour: " + dog.getColour());
System.out.println("");

System.out.println("Fish breed : " + fish.getBreed());


System.out.println("Water type : " + fish.getWaterType());
System.out.println("Fish colour: " + fish.getColour());
}
}

#Animal
package animalshop;

public class Animal {


private String breed;
private String colour;

public Animal(String breed, String colour)


{
this.breed = breed;
this.colour = colour;
}

public String getBreed()


{
return breed;
}

public void setBreed(String breed)


{
this.breed = breed;
}

public String getColour()


{
return colour;
}

public void setColour(String colour)


{
this.colour = colour;
}
}

#Dog
package animalshop;

public class Dog extends Animal


{
private String name;
private String barkNoise = "Woof";
private double weight;

public Dog(String name, String breed, double weight, String colour)


{
super(breed, colour);
this.name = name;
this.weight = weight;
}

public Dog(String name, String breed, String noise, double weight, String colour)
{
super(breed, colour);
this.name = name;
barkNoise = noise;
this.weight = weight;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public double getWeight() {


return weight;
}

public void setWeight(double weight) {


this.weight = weight;
}

public void bark()


{
System.out.println(barkNoise);
}

public void bark(String barkNoise)


{
System.out.println(barkNoise);
}
}
#Fish
package animalshop;

public class Fish extends Animal


{
private String waterType;

public Fish(String breed, String waterType, String colour)


{
super(breed, colour);
this.waterType = waterType;
}

public String getWaterType()


{
return waterType;
}

public void setWaterType(String waterType)


{
this.waterType = waterType;
}
}

Задание 2

Решение:
1. Mutator
2. Accessor
3. ArrayList
4. Inheritance
5. Unit testing
Задание 3
1. If you did not install the JavaBank Case Study during the lesson then
please follow the slides from Slide 6 to do so now.
2. Explore JavaBank. Record your observations. What happens when you:
• Display Accounts
Если аккаунты не созданы, то отображается соответствующая надпись.
Если же созданы, то отображается имя, номер аккаунта и баланс для всех
созданных аккаунтов.
• Create Accounts
Для этого варианта нужно имя клиента и номер счета. Также
программа покажет нам эту инструкцию. Потом отображается имя, номер
аккаунта и счёт
• Delete Accounts
Эта опция еще не закодирована.
• Make a Withdrawal Transaction
Этой опции необходим номер аккаунта и сумма, которую надо вывести
с конкретного счета, после чего счет уменьшается на эту сумму.
• Make a Deposit Transaction
Аналогично с предыдущим, только требуется сумма, которую кладут
на счет, и размер счёта увеличивается.
• Can you display accounts before any are created?
Нет, программа пишет, что еще не созданы аккаунты
• Can you create an account without entering anything in the fields?
Нет, программа требует имя и номер аккаунта
• Can you make a withdrawal transaction with no amount in the Withdrawal
field?
Да, но ничего не изменяется
• Can you do a deposit transaction with no amount in the Deposit field?
Да, но ничего не изменяется
• What other questions do you have about the JavaBank application?
Я не знаю, почему нет кода для кнопки удаления
• What changes would you make to the current application to make it
function better?
Добавила бы кнопку удаления, реализовала исключения в коде или
автоматическое создание номеров счетов для отсутствия повторения
• What additions would you make to the current application to increase its
functionality?
Создала бы учетные записи других типов
3. Download the bikeproject.zip file from Oracle iLearning, unzip the file to
a directory on your local machine. Import the existing project into Eclipse.
a. Give an example of two primitive data types that are used to store fields
within a class
В данной программе есть тип данных int.
b. Give an example of where String concatenation takes place.
System.out.println("\n" + this.make + "\n"
+ "This bike has " + this.handleBars + "
handlebars on a "
+ this.frame + " frame with " + this.NumGears + "
gears."
+ "\nIt has a " + this.seatType + " seat
with " + this.tyres + " tyres.");

c. What are the names of the objects created in this program?


RoadBike, MountainBike, Bike
d. How many constructors does each class have?
Bike: 2
MountainBike: 2
RoadBike: 3
e. Inheritance is part of this program. Identify the Super and subclasses
from this program.
SuperClass: Bike
SubClass: RoadBike, MountainBike
f. Mountain bikes and road bikes can be constructer either by using the
default values (standard bike) or customized to the client’s needs. Using the
following table identify sample values assigned to one of each type of standard
bike:
Для Mountain Bike мы используем конструктор:
public MountainBike()
{
this("Bull Horn", "Hardtail", "Maxxis", "dropper", 27, "RockShox XC32",
"Pro", 19);
}//end constructor
Для Road Bike:
public RoadBike()
{
this("drop", "racing", "tread less", "razor", 19, 20, 22);
}//end constructor

4. Working with the Calculator program.


a. Create a Java Project in Eclipse called calculator.
b. Download and unzip the Calculator.zip file from Oracle iLearning.
c. Import the Calculator.jar file by clicking File, Import, General, Archive
File (make sure you specify the location of the zip file and the name of the project
you want to import it into - Calculator)
d. Once imported – run the application (CalcMain is the driver)
e. Determine what Calculator does and how it works – investigate.
Он просто складывает два числа. Если нажать +, потом на число и
потом на равно, то программа ломается. Если нажать плюс и потом равно, то
она также ломается.
f. Add multiplication and subtraction buttons to the application.
g. Test to make sure all functionality works as you expect.
h. Export updated Calculator to a “Runnable” JAR file.
i. Go to the location where you put the runnable JAR and double click it to
run the application
Задание 4

Решение:
1. Constructor
2. Final
3. Final
4. Interface
Задание 5
Результат работы:
Код программы:
package bikeproject;

public class Bike implements BikeParts{

private String handleBars, frame, tyres, seatType;


private int NumGears;
private final String make;

public Bike(){
this.make = "Oracle Cycles";
}//end constructor

public Bike(String handleBars, String frame, String tyres, String seatType,


int numGears) {
this.handleBars = handleBars;
this.frame = frame;
this.tyres = tyres;
this.seatType = seatType;
NumGears = numGears;
this.make = "Oracle Cycles";
}//end constructor

protected void printDescription()


{
System.out.println("\n" + this.make + "\n"
+ "This bike has " + this.handleBars + "
handlebars on a "
+ this.frame + " frame with " + this.NumGears + "
gears."
+ "\nIt has a " + this.seatType + " seat with " +
this.tyres + " tyres.");
}//end method printDescription

public String getHandleBars()


{
return handleBars;
}
public void setHandleBars(String newValue)
{
this.handleBars = newValue;
}
public String getTyres()
{
return tyres;
}
public void setTyres(String newValue)
{
this.tyres = newValue;
}
public String getSeatType()
{
return seatType;
}
public void setSeatType(String newValue)
{
this.seatType = newValue;
}

}//end class Bike

package bikeproject;

public class BikeDriver {

public static void main(String[] args) {

RoadBike bike1 = new RoadBike();


RoadBike bike2 = new RoadBike("drop", "tourer", "semi-grip", "comfort",
14, 25, 18);
MountainBike bike3 = new MountainBike();
Bike bike4 = new Bike();

bike1.printDescription();
bike2.printDescription();
bike3.printDescription();
bike4.printDescription();
bike1.setPostHeight(20);
bike1.printDescription();

}//end method main

}//end class BikeDriver

package bikeproject;

public interface BikeParts {


//constant declaration
public final String MAKE = "Oracle Bikes";

//required methods after implementation


public String getHandleBars();
public void setHandleBars(String newValue);
public String getTyres();
public void setTyres(String newValue);
public String getSeatType();
public void setSeatType(String newValue);

}//end interface BikeParts

package bikeproject;

public class MountainBike extends Bike implements MountainParts{

private String suspension, type;


private int frameSize;

public MountainBike()
{
this("Bull Horn", "Hardtail", "Maxxis", "dropper", 27, "RockShox XC32",
"Pro", 19);
}//end constructor

public MountainBike(String handleBars, String frame, String tyres, String


seatType, int numGears,
String suspension, String type, int frameSize) {
super(handleBars, frame, tyres, seatType, numGears);
this.suspension = suspension;
this.type = type;
this.frameSize = frameSize;
}//end constructor

public void printDescription()


{
super.printDescription();
System.out.println("This mountain bike is a " + this.type + " bike and
has a " + this.suspension + " suspension and a frame size of " + this.frameSize +
"inches.");

}//end method printDescription

public String getSuspension()


{
return suspension;
}
public String getType()
{
return type;
}
public void setSuspension(String suspension)
{
this.suspension=suspension;
}
public void setType(String type)
{
this.type = type;
}
}//end class MountainBike

package bikeproject;

public interface MountainParts {


final public String TERRAIN = "off_road";
public String getSuspension();
public String getType();

public void setSuspension(String newValue);


public void setType(String newValue);

package bikeproject;

public class RoadBike extends Bike implements RoadParts{

private int tyreWidth, postHeight;

public RoadBike()
{
this("drop", "racing", "tread less", "razor", 19, 20, 22);
}//end constructor

public RoadBike(int postHeight)


{
this("drop", "racing", "tread less", "razor", 19, 20, postHeight);
}//end constructor

public RoadBike(String handleBars, String frame, String tyres, String


seatType, int numGears,
int tyreWidth, int postHeight) {
super(handleBars, frame, tyres, seatType, numGears);
this.tyreWidth = tyreWidth;
this.postHeight = postHeight;
}//end constructor

public void printDescription()


{
super.printDescription();
System.out.println("This Roadbike bike has " + this.tyreWidth + "mm
tyres and a post height of " + this.postHeight + ".");
}//end method printDescription

public int getTyreWidth()


{
return tyreWidth;
}
public int getPostHeight()
{
return postHeight;
}
public void setTyreWidth(int tyreWidth)
{
this.tyreWidth = tyreWidth;
}
public void setPostHeight(int postHeight)
{
this.postHeight = postHeight;
}
}//end class RoadBike
package bikeproject;

public interface RoadParts {

public final String TERRAIN = "track_racing";

int getTyreWidth();
int getPostHeight();
void setTyreWidth(int tyreWidth);
void setPostHeight(int postHeight);
}

You might also like