Вы находитесь на странице: 1из 20

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

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


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

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

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

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

Санкт-Петербург
2020
Выполнение задания
Задание 1
1. Recreate this class that was seen in the previous
package cell;
//класс из лекции для хранения внутри коллекции
//создание собственной коллекции на основе массива

public class Cell {


private String data;

public void setValue(String celldata)


{
data = celldata;
}//end method setValue

public String getValue()


{
return data;
}//end method get

public String toString()


{
return data;
}//end method toString
}//end class Cell
2. Create a class that will act as your own simple data structure (collection) to store multiple
Cell occurrences
Класс без использования generic
package cell;
//класс коллекции из лекции без использования generic
//создание собственной коллекции на основе массива
public class CellCollection
{
Cell[] cells;
int index=0;

public CellCollection(int size)


{
cells = new Cell[size];
}//end constructor

public void add(Cell c)


{
cells[index]=c;
index++;
}//end method add

public Cell get(int i)


{
return cells[i];
}//end method get
}//end class CellCollection
3. Create the following driver class to test the collection
package cell;

//класс из лекции 3.2 для проверки работы коллекции без generic


//создание собственной коллекции на основе массива
public class CellCollectionDriver {
public static void main(String[] args) {
CellCollection cells = new CellCollection(5);
cells.add(new Cell());
cells.add(new Cell());

System.out.println(cells.get(0));
System.out.println(cells.get(1));

cells.get(0).setValue("First Cell");
cells.get(1).setValue("Second Cell");

System.out.println(cells.get(0));
System.out.println(cells.get(1));
}//end method main
}//end class
4. We could try to create a generic collection similar to our non generic example.
Коллекция с использованием generic
package cell;

//класс коллекции из лекции 3.2 c использованием generic


//создание собственной коллекции на основе массива
public class CellGenericCollection<T> {
T[] cells;
int index = 0;

public CellGenericCollection(int size) {


cells = (T[]) new Object[size]; // небезопасное приведение типов
}//end constructor

public void add(T c) {


cells[index] = c;
index++;
}//end method add

public T get(int i) {
return cells[i];
}//end method get
}

Задание 2
1. Create a project named classlist.
2. Сreate a class Student that has a main method.
3. Initialize an ArrayListof Strings called studentNames in the main method.
4. Create a static method named addStudents that adds each student in your
classroom to the ArrayList.
5. Call the addStudents method from main.
6. Create a static method named displayStudents that uses an enhanced for
loop to display the contents of the ArrayList. The output should look
like: Student Name: Mark
7. Call the displayStudents method at the end of main.
8. Collections contains a method called sort that takes in a List as a
parameter and lexicographically sorts the list. An ArrayListis a List so
use the Collections sort method on your ArrayListat the bottom of main.
9. Call the displayStudentsmethod again from main.
Результат работы:

Код программы:
package classlist;
//класс из лекции 3.2
//работа с ArrayList
import java.util.ArrayList;
import java.util.Collections;

public class Student {

public static void main(String[] args) {


// TODO Auto-generated method stub
ArrayList<String> studentNames = new ArrayList<String>(); //создаем
ArrayList строкового типа с именами студентов

addStudents(studentNames); //вызываем метод, который добавляет имена


displayStudents(studentNames);//вызываем метод, который выводит имена
Collections.sort(studentNames);//сортируем коллекцию
System.out.println();
displayStudents(studentNames);//вызываем метод, который выводит имена
}

public static void addStudents(ArrayList<String> studentNames) //метод,


который принимает ArrayList с именами и добавляет новые имена в этот лист
{
studentNames.add("Mark");
studentNames.add("Andrew");
studentNames.add("Beth");
}

public static void displayStudents(ArrayList<String> studentNames) //метод,


который принимает ArrayList с именами и выводит их в консоль
{
for(String student: studentNames)
{
System.out.println("Student Name: "+student);
}
}
}

Задание 3
1. Create a project named hashsetexample.
2. Create the following Coin class:

3. Create a test class that has a main method called CoinTestDriver.


4. The code below demonstrates the initialization of HashSet bagOfCoins. The
HashSet bagOfCoinsis a set of Coin objects.

5. Create a number of coin objects that hold the following denominations (1, 2, 5, 10,
20, 50, 100)
6. Add the coins (1, 2, 5, 10, 20, 50) to the bagOfCoins HashSet. Do not add
coin100! Add coin10 to the HashSettwice!
7. Create a static method named findCointhat accepts the ArrayListand a coin object
as parameters and does not return any values. The method should be called from
main.
8. Use an if statement to check if the bag contains the coin that was passed as the
parameter. If the coin is in the bag then the following output should be displayed:
There is a coin10 in the bag otherwise There is no coin10 in the bag
9. Test it by using coin10 and coin100 for the search
10. Create a static method named displayBagContents that accepts the ArrayListas a
parameter and does not return any values. The method should be called from main.
Use an enhanced for loop to display the denomination value for the coins stored in the
HashSet.
11. Create a static method named displayBagDetailsthat accepts the ArrayListas a
parameter and does not return any values. If the HashSet is empty it should display a
message stating the bag is empty, otherwise display a how many coins are in the bag.
12. Identify the HashSet method that removes all of the elements from the set and
write it directly under the displayBagDetails() method call in main.
13. Call displayBagDetails() again, after you have removed all of the elements from
the set in main

Результат работы:

Код программы:
//Класс CoinTestDriver
package hashsetexample;
//класс из лекции 3.2 для проверки работы
//исследование HashSet
import java.util.HashSet;
public class CoinTestDriver {

public static void main(String[] args)


{
//create the hashset
HashSet<Coin> bagOfCoins = new HashSet<Coin>();

//create coin objects


Coin coin1 = new Coin(1);
Coin coin2 = new Coin(2);
Coin coin5 = new Coin(5);
Coin coin10 = new Coin(10);
Coin coin20 = new Coin(20);
Coin coin50 = new Coin(50);
Coin coin100 = new Coin(100);

//add the coins to the bag


bagOfCoins.add(coin1);
bagOfCoins.add(coin2);
bagOfCoins.add(coin5);
bagOfCoins.add(coin10);
bagOfCoins.add(coin20);
bagOfCoins.add(coin50);
bagOfCoins.add(coin10);

findCoin(bagOfCoins, coin10); //вызываем метод, проверяющий наличие


монеты10
findCoin(bagOfCoins, coin100); //вызываем метод, проверяющий наличие
монеты100
displayBagContents(bagOfCoins); //вызываем метод, который выводит
содержимое сумки
displayBagDetails(bagOfCoins); //вызываем метод, который выведет
количество содержимого в сумке
bagOfCoins.clear(); //очищаем всю сумку
displayBagDetails(bagOfCoins); //вызываем метод, который выведет
количество содержимого в сумке
}//end method main

static void findCoin(HashSet<Coin> bagOfCoins, Coin coin) { //метод, который


проверяет наличие монеты в сумке
if (bagOfCoins.contains(coin)) //если монета есть в сумке
System.out.println("There is a coin" + coin.getDenomination() + "
in the bag"+"\n");
else //если ее нет
System.out.println("There is no coin" + coin.getDenomination() +
" in the bag"+"\n");
}

static void displayBagContents(HashSet<Coin> bagOfCoins) //метод, который


выводит содержимое сумки
{
for (Coin coin : bagOfCoins)
System.out.println(coin.getDenomination());
System.out.println();
}

static void displayBagDetails(HashSet<Coin> bagOfCoins) //метод, который


отображает количество содержимого в сумке
{
if (bagOfCoins.isEmpty()) //если сумка пустая
System.out.println("There are no coins in the bag");
else //если в ней что-то есть
System.out.println("There are " + bagOfCoins.size() + "
coins in the bag \n");
}
}//end class CoinTestDriver

//Class Coin
package hashsetexample;
//класс из лекции 3.2
//исследование HashSet
//класс для хранения внутри HashSet
public class Coin {
private int denomination;

public Coin(int denomination)


{
this.denomination = denomination;
}//end constructor

public int getDenomination()


{
return denomination;
}//end getDenomination
}//end class Coin

Задание 4

Результат работы:
HashSet - A set similar to an ArrayList without any specific ordering.
List - An ordered Collection that may contain duplicates.
Collection - An interface used to define a group of objects. This includes lists and sets.
ArrayList - A list that is very similar to an array.
Set - A Collection of elements that does not contain any duplicates.

Задание 5
1. This activity uses the javabank project, open it in the IDE. You are going to update the
code to use an ArrayList instead of a static one dimensional array.
a. Open the javabank.java file.
b. Find the line that creates the static one-dimensional array named myAccounts
static AbstractBankAccount myAccounts[] = new
AbstractBankAccount[MAXACCOUNTS];
c. Comment out that line and create an ArrayList of AbstractBankAccount named
myAccounts directly underneath it.
//static AbstractBankAccount myAccounts[] = new
AbstractBankAccount[MAXACCOUNTS]; static ArrayList<AbstractBankAccount>
myAccounts = new ArrayList<AbstractBankAccount>();
myAccounts[noAccounts] = new CreditAccount(name,accountNum,balance);

becomes
myAccounts.add(new CreditAccount(name,accountNum,balance));

myAccounts[i].setBalance(myAccounts[i].getBalance()+deposit);

becomes
myAccounts.get(i).setBalance(myAccounts.get(i).getBalance()+deposit);
e. Run and test the java application by creating multiple accounts of various types and displaying
the
d. Identify all of the errors that now appear in the code and update them using the add() or get()
methods to work with the ArrayList.

Задание 6
Код программы:
package bikeproject;

import java.util.ArrayList;
import java.util.Random;
// класс, созданный по описанию из практики
//использование ArrayList для хранения Bike
public class BikeList {

public static void main(String[] args) {


ArrayList<Bike> bikes = new ArrayList<>();
int mountainBikeSales=0;
int roadBikeSales=0;

fillArray(bikes);
displayStock(bikes);
displayBikeNumbers(bikes);
}

public static void fillArray(ArrayList<Bike> b){ // случайное заполнение


списка 10 элементами
Random r = new Random();
for (int i =0; i<10; i++){
int k = r.nextInt(2);
if (k==0){
b.add(new MountainBike());
}
else
{
b.add(new RoadBike());
}
}
}

public static void displayStock(ArrayList<Bike> bike){ //отображает байки в


консоль
for (Bike i: bike) {
System.out.println(i);
}
}

public static int calculateStock(ArrayList<Bike> bike){ // подсчет количества


MountainBike в списке
int bikesSold = 0;
for (Bike i:bike){
if (i instanceof MountainBike)
bikesSold++;
}
return bikesSold;
}

public static void displayBikeNumbers(ArrayList<Bike> b){ // подсчет и вывод


количества объектов каждого класса в списке
int mb, rb;
mb = calculateStock(b);
rb = b.size()-mb;
System.out.println("Stock Levels\nWe have "+mb+" Mountain Bikes\nWe have
"+rb+" Road Bikes");
}
}

Задание 7
1. What is the difference between a set and a list?
Ответ: Лист может содержать несколько одинаковых элементов
2. You decide you want to roll 2 dice and see what the frequency is of each possible number
combination. Would you use a Set collection to do this? State your reason(s).
Ответ: Нет, так как set не может содержать одинаковых результатов выпадания
3. Using a collection create a variable that will store a list of countries (Strings). Your
collection should not store duplicates, and order is not important. Test your code by
adding 6 countries, one of which is a duplicate.
Ответ: HashSet <String> countries = new HashSet<>();
countries.add("Russia");
countries.add("Ukraine");
countries.add("Vietnam");
countries.add("USA");
countries.add("China");
countries.add("Russia");
for (String i:countries)
System.out.println(i);
4. Would the following Collection.sort() statements both work? Explain your answer.
HashSet<String> countriesSet = new HashSet<String>();
Collections.sort(countriesSet);
ArrayList<String> countriesList = new ArrayList();
Collections.sort(countriesList);
Ответ: HashSet нельзя сортировать.

Задание 8
1. Create a project named hashsetexample.
2. Create a HashMapExampleclass that includes a main method.
3. Initialize a HashMap named fruitBowlthat will hold 2 String values.
4. Create an AddElementsmethod that accepts the HashMap as a parameter and add an apple
using the put(Key,Value) function of the HashMap collection
5. Add the following fruits to the fruitBowl.
6. Create a displayElementsmethod that accepts the HashMap as a parameter and will be used
to display the values of the HashMap.
7. To simply check the contents of the HashMap you can include its name in an output
statement.
8. To format the output to suit your need you can use an enhanced for loop.
9. Add a red apple to the bottom of the add elements method to see that you lose the green
apple.
10.Create the following method that will check if the fruit exists in the bowl and then display its
value to screen or else display a fruit not found method.
Результат работы:

Код программы:
package hashmapexample;
//класс из лекции 3.3
//использование HashMap
import java.util.HashMap;

public class HashMapExample {


public static void main(String[] args)
{
HashMap<String,String> fruitBowl = new HashMap<String, String>();
addElements(fruitBowl);
displayElements(fruitBowl);
findElement(fruitBowl, "Banana");
}//end method main

static void findElement(HashMap<String, String> fruitBowl, String fruit)


{
if(fruitBowl.containsKey(fruit))
System.out.println("The " + fruit + " is " +
fruitBowl.get(fruit));
else
System.out.println("There is no " + fruit + " in the bowl");
//endif
}//end method findElement

static void addElements(HashMap<String, String> fruitBowl)


{
fruitBowl.put("Apple", "Green");
fruitBowl.put("Cherry", "Red");
fruitBowl.put("Orange", "Orange");
fruitBowl.put("Banana", "Yellow");
fruitBowl.put("Apple", "Red");
}//end method addElements
static void displayElements(HashMap<String, String> fruitBowl)
{
//System.out.println(fruitBowl);
for (HashMap.Entry<String, String> fruit : fruitBowl.entrySet())
{
System.out.println("Fruit: " + fruit.getKey() +" - Color:
"+fruit.getValue());
}//endfor
}//end method displayElements
}//end class HashMapExample

Задание 9
1. Create a project named lettersqueue.
2. Create a class named LettersQ.
3. Initialize a LinkedList of String named lettersQ.
4. Use the add method to add elements to the Stack.
5. Display the contents and size of the Queue.
6. Use a while loop to remove the first element from the Queue and display them to the
console while the Queue is not empty. Display the empty Queue after.
Результат работы:

Код программы:
package lettersqueue;

import java.util.LinkedList;

//класс из лекции
//очередь с использованием LinkedList;
public class LettersQ {
public static void main(String[] args) {
LinkedList<String> lettersQ = new LinkedList<String>();
lettersQ.add("A");
lettersQ.add("B");
lettersQ.add("C");
lettersQ.add("D");
// display the contents of the linked list
System.out.println("Linked list : " + lettersQ);
// display the size of the linked list
System.out.println("Queue Size: " + lettersQ.size());

while (!lettersQ.isEmpty()) {
System.out.println(lettersQ.removeFirst());
}
System.out.println("Linked list : " + lettersQ);
}
}
Задание 10
1. Create a project named lettersstack.
2. Create a class named LettersS.
3. Initialize a LinkedList of String named lettersStack.
4. Use the push method to add elements to the Stack
5. Display the contents and size of the Stack.
6. Use a while loop to remove (pop) elements from the Stack and display them to the console
while the Stack is not empty. Display the empty Stack after.
Результат работы:

Код программы:
package lettersqueue;

import java.util.LinkedList;
//класс из лекции
//стэк с использованием LinkedList;
public class LettersS {
public static void main(String[] args) {
LinkedList<String> letterStack = new LinkedList<String>();

letterStack.push("A");
letterStack.push("B");
letterStack.push("C");
letterStack.push("D");

// display the contents of the linked list


System.out.println("Linked list : " + letterStack);
// display the size of the linked list
System.out.println("Stack Size: " + letterStack.size());
while (!letterStack.isEmpty()) {
System.out.println(letterStack.pop());
}
System.out.println("Linked list : " + letterStack);
}
}

Задание 11
1. Create a classlistobjproject.
2. Create a Student class that does not have a main method. It should have the following
instance fields and constructor
3. Create getters and setters for all of the instance fields
4. Create a toStringmethod that will return the value of the instance fields
5. Implement the Comparable interface in the Student class.
6. When the Comparable interface is implemented it forces the inclusion of compareTo()
method. This will be used for the Collections.sortmethod.
7. Create a driver class that will add students and then display them to screen.
8. Run and test your code to check that it works.
9. Update the code to sort the students by their mark.
10. To compare based on a primitive data type the valueOfmethod must be invoked. This
returns an Integer instance based on the value of the primitive. Update the code to use this
method
Результат работы:

Код программы:
package queueStackSort;

//класс из лекции
//сортировка и compareTo
//класс, который будет находиться в сортируемом массиве;
public class Student implements Comparable<Student> {
private String firstName;
private String lastName;
private int mark;

public Student(String firstName, String lastName, int mark) {


this.firstName = firstName;
this.lastName = lastName;
this.mark = mark;
}//end constructor

public String getFirstName() {


return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getMark() {
return mark;
}
public void setMark(int mark) {
this.mark = mark;
}
public String toString() {
return "Student Details: " + firstName + " " + lastName + " " + mark;
}//end method toString

/* @Override
public int compareTo(Student arg0) { // метод, используемый внутри сортировок,
определяющий взаимное расположение элементов
//сортировка по фамилии
if (lastName.compareTo(arg0.getLastName()) < 0)
return -1;
if (lastName.compareTo(arg0.getLastName()) == 0)
return 0;
return 1;
} */
@Override
public int compareTo(Student stud2) //сортировка по оценке
{
if((Integer.valueOf(mark).compareTo(Integer.valueOf(stud2.getMark())) <
0 ))
return -1;
if((Integer.valueOf(mark).compareTo(Integer.valueOf(stud2.getMark())) ==
0 ))
return 0;
return 1;
}//end method compareTo
} //end class Student

Задание 12

Результат работы:
LinkedList - A double-ended queue; a queue that can add and remove elements to the
front or back of the list.
Nodes - The links of a LinkedList.
Collection - An interface used to define a group of objects. This includes lists and sets.
Maps that link a Key to a Value and may have duplicate Keys but cannot have duplicate Values.
LinkedList - A list of elements that is dynamically stored.
Queue - A list of elements with a first in first out ordering.

Задание 13
1. What is the difference between a Queue and a Stack? Give an example of each.
Ответ: Queue – FIFO {}->{a}->{a,b}->{a,b,c}->{b,c}->{c}->{}
Stack – FILO {}->{a}->{a,b}->{a,b,c}->{a,b}->{a}->{}
2.

Ответ:
package genericstack;

import java.util.ArrayList;

public class GenericStack<T>{


ArrayList<T> items;
int top;
public GenericStack()
{
items = new ArrayList<>();
top=0;
}

public void push(T i)


{
items.add(i);
top++;
}

public T pop()
{
if (top==0)
{
new GenericStackException();
return null;
}
T i = items.remove(top-1);
top--;
return i;
}
public boolean isEmpty()
{
return top==0;
}
public static void main(String[] args)
{
GenericStack<Integer> s = new GenericStack<>();
for (int i=0; i<4; i++)
s.push(i);
for (int i=0; i<5; i++)
System.out.println(s.pop());
}
}

3. Is it possible to add nodes to the beginning of a LinkedList? If so, how? What about adding a
node to the end of a LinkedList? If this can be done, what method would be used?
Ответ: Да, это осуществимо с помощью методов add() и addLast()
4. What is the purpose of implementing the Comparable interface in one of our classes?
Ответ: Comparable interface имеет метод compareTo, который используется некоторыми
методами, такими как сортировка.
5.

a. Print out the list of courses.


b. Use the get method on one of the course codes to get the course name.
Ответ: package genericstack;
import java.util.HashMap;
//класс из практики 3.3 с курсами
public class Courses {
public static void main(String[] args)
{
HashMap<String, String> map = new HashMap<>();
map.put("CIT", "Computing and Information Technology");
map.put("CHI", "Childcare and Early Education");
map.put("MVS", "Motor Vehicle Systems");
map.put("BTH", "Beauty Therapy");
map.put("GDE", "Graphic Design");

for (String s: map.keySet())


{
System.out.println(s+" : "+map.get(s));
}
}
}

Display the contents and size of the Stack.


6. Use a while loop to remove (pop) elements from the Stack and display them to the console
while the Stack is not empty. Display the empty Stack after.
Результат работы:

Код программы:

Задание 14
1. Create a project named lettersstack.
2. Create a class named LettersS.
3. Initialize a LinkedList of String named lettersStack.
4. Use the push method to add elements to the Stack
5. Display the contents and size of the Stack.
6. Use a while loop to remove (pop) elements from the Stack and display them to the console
while the Stack is not empty. Display the empty Stack after.
Результат работы:

Код программы:

Задание 15
1. Create a project named lettersstack.
2. Create a class named LettersS.
3. Initialize a LinkedList of String named lettersStack.
4. Use the push method to add elements to the Stack
5. Display the contents and size of the Stack.
6. Use a while loop to remove (pop) elements from the Stack and display them to the console
while the Stack is not empty. Display the empty Stack after.
Результат работы:
Код программы:

Вам также может понравиться