Java, exercício de análise

assunto: excepções
pergunta: qual o output do seguinte:

package recursopa2;

class MyException extends Exception {
}

class main {
    static void f(int n) throws MyException {
        try {
            if (n > 0) {
                throw new MyException();
            }
            System.out.print("fl ");
        } catch (MyException e) {
            System.out.print("f2 ");
            //saida: f2
        } finally {
            System.out.print("f3 ");
            //saida: f3
        }
        System.out.print("f4 ");
        //saida: f4
    }

    public static void main(String[] args) {
        try {
            f(2);
            System.out.print("ml ");
            //saida: m1
        } catch (MyException e) {
            System.out.print("m2 ");
        }
        System.out.print("m3 ");
        //saida: m3
    }
}

assunto: classes concreta (não abstracta)
pergunta: qual o output do seguinte:

interface IMove {
    void move();
}

interface IJump extends IMove {
    default void jump() {
        System.out.println(" jump ");
    }
    int getHeight();
}

class Kanguru implements IJump {
//para se tornar numa classe concreta, tem que ter todos os métodos anteriores
    public void jump() {
    }
    public void move() {
    }
    public int getHeight() {
        return 1;
    }
}

assunto: equals, arrays, hashCode, hashSet
pergunta: qual o output do seguinte:

package recursopa2;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

class Product {

    private String id;
    private int stockQt;

    public Product(String id, int q) {
        this.id = id;
        this.stockQt = q;
    }

    public boolean sell(int n) {
        if (stockQt >= n) {
            stockQt -= n;
            return true;
        }
        return false;
    }

    @Override
    public boolean equals(Object ob) {
        if (ob == null || getClass() != ob.getClass()) {
            return false;
        }
        return id.equals(((Product) ob).id);
    }

    @Override
    public int hashCode() {
        return this.stockQt;
    }
}

public class main {

    public static void main(String[] args) {
        Product a = new Product("idA", 10);
        Set<Product> set = new HashSet<>();
        set.add(a);
        a.sell(4);
        System.out.print(" Contains? " + set.contains(a));
        //supostamente estas a comparar com o equals endereços de memória
        //saida: falso
        
        Product b = new Product("id8", 10);
        List<Product> list = new ArrayList<>();
        list.add(b);
        b.sell(4);
        System.out.print(" Contains? " + list.contains(b));
        //sendo um array..
        //saida: true
    }
}

assunto: classes derivadas, super
pergunta: qual o output do seguinte:

package recursopa2;

class Bird {

    private String name;

    public Bird(String s) {
        name = s;
    }

    @Override
    public String toString() {
        return name;
    }
}

class Swallow extends Bird {

    public Swallow(String s) {
        //line A
        super(s);
    }

    public String toString() {
        // line B
        return super.toString() + "Swallow";
    }
}

public class main {

    public static void main(String[] args) {
        Swallow objl = new Swallow(" from Africa ");
        Swallow obj2 = new Swallow(" from the islands ");
        System.out.println(objl + " " + obj2);
        //saida: from Africa Swallow from the islands Swallow
    }
}

assunto: classes derivadas
pergunta: qual o output do seguinte:

package recursopa2;

interface IMove {
    void move(); //mover 
}

interface IFly extends IMove {

    void fly(); //voar
}

class Gaivota implements IFly {

    public void move() {
        System.out.println("move");
    }

    public void fly() {
        System.out.println("fly");
    }
}

class main {

    public static void main(String[] args) {
        IMove a = new IMove();  //linha 1
        //erro: IMove, é uma interface, é abstracta 
        
        IMove[] b = new IFly[4];  //linha 2
        IFly c = new Gaivota();  //linha 3
        IMove d = new Gaivota(); //linha 4
        c.move(); //linha 5
        c.fly(); //linha 6
        d.fly(); //linha 7
        //erro: o método fly nao faz parte de IMove
        
        d.move(); //linha 8
        c = d; //linha 9
        //erro: não da para coverter tipos diferentes
        
        d = c; //linha 10
    }
}

assunto: máquina de estados, state machine
pergunta: pretende desenvolver uma nova versão da classe MTThread sob a forma de uma máquina de estados orientada a objectos. Recorra, para o efeito, ao padrão estudado nas aulas laboratoriais e aplicado ao trabalho prático de modo a que uma thread passe a ser uma instância de uma classe que, entre outros atributos, inclua o seu estado actual e tire partido do polimorfismo ao nível dos estados.

package recursopa2;

class MTThread {

    public static enum Const {
        WAII_START, WAII_TO_BE_SCHEDULED, TERMINATED,
        YELD_INVOKED, RUNNING, SCHEDULE_COMPLETED, UNBLOCKED,
        SLEEP_COMPLETED, BLOCKED, SLEEPING, SLEEP_INVOKED
    };
    private Const situation;
    private Data data;

    // Some hidden stuff you don't have to worry about
    //(constructors, getters, ...J
    /* ... */
    public Const getSituation() {
        return situation;
    }

    public void start() {
        if (situation == Const.WAII_START) {
            situation = Const.WAII_TO_BE_SCHEDULED;
        }
    }

    public void schedule() {
        if (situation == Const.WAII_TO_BE_SCHEDULED) {
            situation = Const.RUNNING;
        }
    }

    public void doSomething() {
        if (situation == Const.RUNNING) {
            Const result = data.doSomething();
            switch (result) {
                case YELD_INVOKED:
                    situation = Const.WAII_TO_BE_SCHEDULED;
                    break;
                case BLOCKED:
                    situation = Const.BLOCKED;
                    break;
                case SLEEP_INVOKED:
                    situation = Const.SLEEPING;
                    break;
                case TERMINATED:
                    situation = Const.TERMINATED;
                    break;
                default:
                    break;
            }
        }
    }

    public void scheduleCompleted() {
        if (situation == Const.WAII_TO_BE_SCHEDULED) {
            situation = Const.RUNNING;
        }
    }

    public void unblocked() {
        if (situation == Const.BLOCKED) {
            situation = Const.WAII_TO_BE_SCHEDULED;
        }
    }

    public void sleepCompleted() {
        if (situation == Const.SLEEPING) {
            situation = Const.WAII_TO_BE_SCHEDULED;
        }
    }
}

resposta:

interface IStates {
    Const getSituation();
    IStates start();
    IStates schedule();
    IStates doSomething();
    IStates scheduleCompleted();
    IStates unblocked();
    IStates sleepCompleted();
}

assunto: máquina de estados, state machine
pergunta: implemente uma classe StateAdapter que implemente a interface IStates e a partir da qual derivam todos os estados da nova versão da máquina de estados MTThread

public class StateAdapter implements IStates {
    @Override
    public Const getSituation() {
        return this;
    }

    @Override
    IStates start() {
        return this;
    }

    @Override
    IStates schedule() {
        return this;
    }

    @Override
    IStates doSomething() {
        return this;
    }

    @Override
    IStates scheduleCompleted() {
        return this;
    }

    @Override
    IStates unblocked() {
        return this;
    }

    @Override
    IStates sleepCompleted() {
        return this;
    }
}

assunto: máquina de estados, state machine, IStates
pergunta: implemente uma classe que representa o estado em que a thread se encontra bloqueada na nova versão da máquina de estados MTThread

class Blocked extends StateAdapter{
    @Override
    IStates unblocked(){
        return new WaitToBeScheduled();
    }
}

assunto: máquina de estados, state machine
pergunta: As classes Defender e Forward representam jogadores de futebol, sendo ambas derivadas da classe Player. A classe Club contém uma coleção de jogadores que podem ser do tipo Defender ou Forward. A classe Club permite acrescentar jogadores e saber o número de jogadores que contém. Escreva o código necessário para que a criação de objetos do tipo Player seja feita utilizando o padrão Fábrica de Objetos e complete a função addPlayer() da classe Club, utilizando este padrão.

package recursopa2;

import java.util.ArrayList;
import java.util.List;

enum PlayerTypes {
    DEFENDER, FORWARD
}

abstract class Player {
    private String name;

    public Player(String name) {
        this.name = name;
    }
    //...
}

class Defender extends Player {
    public Defender(String name) {
        //...
    }
    //...
}

class Forward extends Player {
    public Forward(String name) {
        //...
    }
    //...
}

class Club {
    private List<Player> players = new ArrayList<>();
    //...

    public void addPlayer(PlayerTypes type, String name) {
        // Fazer : usar a fabrica de objetos do tipo Player
    }

    public int getNumPlayers() {
        return players.size();
    }
}

resposta:

 public void addPlayer(PlayerTypes type, String name) {
  switch (type) {
            case DEFENDER:
                players.add(new Defender(name));
                break;
            case FORWARD:
                players.add(new Forward(name));
                break;
        }
}

assunto: PropertyChangeListener, propertyChange
pergunta: A classe ClubPanel faz parte do interface de utilizador gráfico para objetos de Club, tendo o objetivo de mostrar o número de jogadores do clube, sempre atualizado. Acrescente o necessário à classe ClubPanel de modo a cumprir este objetivo

package recursopa2;

import java.beans.PropertyChangeEvent;

class ClubPanel extends VBox {

    private ObservableClub modelObs;// ligacao ao modelObs
    private Label nPlayers;

    public ClubPanel(ObservableClub model) {
        this.modelObs = model;
        nPlayers = new Label("N. players " + modelObs.getNumPlayers());
        getChildren().addAll(nPlayers);
        setSpacing(5);
        setPadding(new Insets(10, 10, 10, 10));
        setAlignment(Pos.CENTER);
        modelObs.addPropertyChangeListener(this);
    }

    //resposta:
    private void updateNumberOfPlayers(){
        nPlayers.setText("N. players" + modelObs.getNumPlayers());
    }
    @Override
    public void propertyChange(PropertyChangeEvent ev){
        updateNumberOfPlayers();
    }
}

assunto: máquina de estados, state machine
pergunta: Idealize um diagrama que represente a máquina de estados MTThread de forma adequada, com atribuição de nomes aos estados e às transições/métodos coincidentes com os da listagem. Deve representar todas as transições que podem ocorrer entre os estados. Descreva este diagrama de forma textual seguindo o formato usado no seguinte exemplo (estado [condição] => próximo estado):

e

package recursopa2;

class MTThread {

    public static enum Const {
        WAII_START, WAII_TO_BE_SCHEDULED, TERMINATED,
        YELD_INVOKED, RUNNING, SCHEDULE_COMPLETED, UNBLOCKED,
        SLEEP_COMPLETED, BLOCKED, SLEEPING, SLEEP_INVOKED
    };
    private Const situation;
    private Data data;

    // Some hidden stuff you don't have to worry about
    //(constructors, getters, ...J
    /* ... */
    public Const getSituation() {
        return situation;
    }

    public void start() {
        if (situation == Const.WAII_START) {
            situation = Const.WAII_TO_BE_SCHEDULED;
        }
    }

    public void schedule() {
        if (situation == Const.WAII_TO_BE_SCHEDULED) {
            situation = Const.RUNNING;
        }
    }

    public void doSomething() {
        if (situation == Const.RUNNING) {
            Const result = data.doSomething();
            switch (result) {
                case YELD_INVOKED:
                    situation = Const.WAII_TO_BE_SCHEDULED;
                    break;
                case BLOCKED:
                    situation = Const.BLOCKED;
                    break;
                case SLEEP_INVOKED:
                    situation = Const.SLEEPING;
                    break;
                case TERMINATED:
                    situation = Const.TERMINATED;
                    break;
                default:
                    break;
            }
        }
    }

    public void scheduleCompleted() {
        if (situation == Const.WAII_TO_BE_SCHEDULED) {
            situation = Const.RUNNING;
        }
    }

    public void unblocked() {
        if (situation == Const.BLOCKED) {
            situation = Const.WAII_TO_BE_SCHEDULED;
        }
    }

    public void sleepCompleted() {
        if (situation == Const.SLEEPING) {
            situation = Const.WAII_TO_BE_SCHEDULED;
        }
    }
}

resposta:

States:
WAIT_START, WAIT_TO_BE_SCHEDULED, 
TERMINATED, RUNNING, BLOCKED, SLEEPING

Transitions:
WAIT_START
start()=>WAIT_TO_BE_SCHEDULED
WAIT_TO_BE_SCHEDULED
schedule()=>RUNNING
TERMINATED
RUNNING
doSomething()[result = YELD_INVOKED] => WAII_TO_BE_SCHEDULED
doSomething()[result = BLOCKED] => BLOCKED
doSomething()[result = SLEEP_INVOKED] => SLEEPING
doSomething()[result = TERMINATED] => TERMINATED
scheduleCompleted() => WAII_TO_BE_SCHEDULED
BLOCKED
unblocked() =>WAII_TO_BE_SCHEDULED
SLEEPING
sleepCompleted() =>WAII_TO_BE_SCHEDULED

Tags : ,

0 thoughts on “Java, exercício de análise”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.