Loading...

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

Olegati avatar Olegati 7 Точки

Java Advanced Exam - 22 Feb 2020 problem 03. Guild 88/100

Здравейте, 

От изпита Java Advanced Exam - 22 Feb 2020 на задача 03.Guild последният 9-ти тест гърми. Предполагам, че методът 

kickPlayersByClass(String clazz)  е причината теста да гърми, но не мога да намеря грешката. 

Player class-a -> https://pastebin.com/V2EdbHRb

Guild class-a -> https://pastebin.com/RE0Xw4mX

Main class-a -> https://pastebin.com/XbKtEQ6s

Линк към Judge -> https://judge.softuni.org/Contests/Practice/Index/2036#2


Условието на задачата: 

Your task is to create a repository which stores players by creating the classes described below.

Player

First, write a Java class Player with the following fields:

  • name: String
  • clazz: String
  • rank: String – "Trial" by default
  • description: String – "n/a" by default

The class constructor should receive name and clazz. You need to create the appropriate getters and setters. Override the toString() method in the following format:

"Player {name}: {clazz}

Rank: {rank}

Description: {description}"

Guild

Next, write a Java class Guild that has a roster (a collection which stores Player entities). All entities inside the repository have the same fields. Also, the Guild class should have those fields:

  • name: String
  • capacity: int

The class constructor should receive name and capacity, also it should initialize the roster with a new instance of the collection. Implement the following features:

  • Method addPlayer(Player player) - adds an entity to the roster if there is room for it
  • Method removePlayer(String name) - removes a player by given name, if such exists, and returns boolean
  • Method promotePlayer(String name) - promote (set his rank to "Member") the first player with the given name. If the player is already a "Member", do nothing.
  • Method demotePlayer(String name)- demote (set his rank to "Trial") the first player with the given name. If the player is already a "Trial",  do nothing.
  • Method kickPlayersByClass(String clazz) - removes all the players by the given class and returns all removed players from that class as an array
  • Method count() - returns the number of players
  • Method report() - returns a String in the following format:
    • "Players in the guild: {guildName}:
      {Player1}
      {Player2}
      (…)
      "

Constraints

  • The names of the players will be always unique.
  • You will always have a player added before receiving methods manipulating the Guild's players.

Examples

This is an example how the Guild class is intended to be used.

Sample code usage

package guild;

public class Main {
    public static void main(String[] args) {

        //Initialize the repository (guild)
        Guild guild = new Guild("Weekend Raiders", 20);
        //Initialize entity
        Player player = new Player("Mark", "Rogue");
        //Print player
        System.out.println(player);

        //Player Mark: Rogue
        //Rank: Trial
        //Description: n/a

        //Add player
        guild.addPlayer(player);
        System.out.println(guild.count()); //1
        System.out.println(guild.removePlayer("Gosho")); //false

        Player firstPlayer = new Player("Pep", "Warrior");
        Player secondPlayer = new Player("Lizzy", "Priest");
        Player thirdPlayer = new Player("Mike", "Rogue");
        Player fourthPlayer = new Player("Marlin", "Mage");

        //Add description to player
        secondPlayer.setDescription("Best healer EU");

        //Add players
        guild.addPlayer(firstPlayer);
        guild.addPlayer(secondPlayer);
        guild.addPlayer(thirdPlayer);
        guild.addPlayer(fourthPlayer);

        //Promote player
        guild.promotePlayer("Lizzy");

        //Remove Player
        System.out.println(guild.removePlayer("Pep")); //true

        Player[] kickedPlayers = guild.kickPlayersByClass("Rogue");
        for (Player kickedPlayer : kickedPlayers) {
            System.out.print(kickedPlayer.getName() + " ");
        }
        //Mark Mike

        System.out.println(guild.report());
        //Players in the guild: Weekend Raiders:
        //Player Lizzy: Priest
        //Rank: Member
        //Description: Best healer EU
        //Player Marlin: Mage
        //Rank: Trial
        //Description: n/a
    }
}

Тагове:
0
Java Advanced
svephoto avatar svephoto 1191 Точки

Здрашей, Olegati,

 

Проблемът не е в метода, за който си мислиш, а тук:

 

public String report() {
    StringBuilder output = new StringBuilder();

    output.append(String.format("Players in the guild: %s:%n", this.name));

    for (int i = 0; i < this.roster.size(); i++) {
        output.append(this.roster.get(i).toString())
                .append(System.lineSeparator());
    }

    return output.toString().trim();
}

 

Липсва ти добавяне на нов ред накрая след всеки играч при итерирането за отделните играчи - виж как изглежда принтирането като стартираш main метода и ти отпечата нещата на конзолата. Слагаме и .trim(), за да сме спокойни, че няма да имаме някой излишен нов ред когато връщаме резултата.

0
09/09/2021 23:32:27
Olegati avatar Olegati 7 Точки

Благодаря, действително това е проблема yes

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