Question

In: Computer Science

complete this code for me, this is java question. // Some comments omitted for brevity import...

complete this code for me, this is java question.

// Some comments omitted for brevity

import java.util.*;

/*
* A class to demonstrate an ArrayList of Player objects
*/
public class ListOfPlayers
{
// an ArrayList of Player objects
private ArrayList players;

public ListOfPlayers()
{
// creates an empty ArrayList of Players
players = new ArrayList<>();
}

public void add3Players()
{
// adds 3 Player objects
players.add(new Player("David", 10));
players.add(new Player("Susan", 5));
players.add(new Player("Jack", 25));
}
  
public void displayPlayers()
{
// asks each Player object to display its contents
// - what if the list is empty?
for (Player currentPlayer : players)
currentPlayer.display();
}
  
// Q.4(a) for Week 8
public void clearPlayers()
{
/* Add code to clear all the Player objects from the ArrayList
* (ie. the list will be emptied after the operation)
*
* Hints:
* - display the list before AND after the operation to check
* if it was performed correctly
*/
  
// wrote your code here...
players.clear();
}

// Q.4(b) for Week 8
public void addPlayer()
{
/* Add code to ask user to input a name and a position,
* then use the data to add a new Player object into the
* players attribute.
*
* There is no need for any input validations.
*
* Hints:
* - use a Scanner to get user inputs
* - create a new Player object
* - use the add() method of the ArrayList class to add it into the list
*/
  
// wrote your code here...
}

// Q.4(c) for Week 8
public int findPlayer(String name)
{
int index = -1;
  
/* Add code to allow user to search for an existing Player object
* in players. The parameter is a string representing the name
* of the Player object to search. The return value is the index
* where the object is found, or -1 if the object is not found.
*
* Assume there are no duplate names in the list.
*
* Hints:
* - use a loop to search through the ArrayList
* - compare the given name to each Player's name in the list
* - use the indexOf() method to return the required index
*/
  
// wrote your code here...
  
return index;
}

// Q.4(d) for Week 8
public boolean updatePlayerName(int index)
{
boolean success = false;
  
/* Add code to allow user to modify an existing Player object
* in players. The parameter is the index to the Player object
* in the ArrayList. Your code should first check if the given
* index is within the correct range (between 0-max, where max
* if the ize of the list. If the index is not valid,
* or the player list is empty,
* print out an error message, otherwise ask the user to input
* a new name and update the Player object with that name.
* If the update operation is successful, return true (otherwise
* return false).
*
* Hints:
* - check if index is valid and list is not empty
* - if yes, use it to get at the correct Player in the list
* - update the Player's name
* - return the appropriate boolean result
*/

// wrote your code here...
  
return success;
}
  
// *** Pre-tute Task 1 for Week 9 ***
public boolean removePlayer(String name)
{
boolean success = false;
  
/* Add code to allow user to remove an existing Player object
* in players. The parameter is the name of the Player object
* to be removed. Your code should first check if th object
* with that name does exist.
*
* Your code *MUST* make a call to the findPlayer() method you
* wrote in Q.4(c) above.
*
* If the remove operation is successful, return true (otherwise
* return false, and print a simple error message).
*
* Hints:
* - use the findPlayer() method to find the position of the object
* - remove the Player if it exists
* - return the appropriate boolean result
*/
  
// wrote your code here...
  
return success;
}
  
// *** Pre-tute Task 2 for Week 9 ***
public boolean updatePlayerName(String oldName, String newName)
{
boolean success = false;
  
/* Add code to allow user to modify an existing Player object
* in players. This time the method takes 2 parameters: oldName
* is the name for an Player object to be searched for, newName
* is the name to update the object with. Your code should first
* check if the object with the oldName does exist.
*
* Your code *MUST* make a call to the findPlayer() method you
* wrote in Q.4(c) above.
*
* If the update operation is successful, return true (otherwise
* return false, and print a simple error message).
*
* Hints:
* - use the findPlayer() method to find the position of the object
* - update the Player's name with the given parameter (newName)
* - return the appropriate boolean result
*/
  
// wrote your code here...

return success;
}
}

Solutions

Expert Solution

ListOfPlayers.java

import java.util.ArrayList;
import java.util.Scanner;

public class ListOfPlayers {
   //I changed from a generic ArrayList to parameterized ArrayList
   //Otherwise the for-each loop will give error in displayPlayers method
  
   private ArrayList<Player> players;

   public ListOfPlayers()
   {
       // creates an empty ArrayList of Players
       players = new ArrayList<Player>();
   }

   public void add3Players()
   {
       // adds 3 Player objects
       players.add(new Player("David", 10));
       players.add(new Player("Susan", 5));
       players.add(new Player("Jack", 25));
   }
  
   public void displayPlayers()
   {
       // asks each Player object to display its contents
       // - what if the list is empty?
       for (Player currentPlayer : players)
           currentPlayer.display();
      
       //For loop is inherently safe against empty, if the list is empty,
       //It never executes.
   }
  
   // Q.4(a) for Week 8
   public void clearPlayers()
   {
       /* Add code to clear all the Player objects from the ArrayList
       * (ie. the list will be emptied after the operation)
       *
       * Hints:
       * - display the list before AND after the operation to check
       * if it was performed correctly
       */
       //Display old players
       this.displayPlayers();
       players.clear();
       this.displayPlayers();
   }

   // Q.4(b) for Week 8
   public void addPlayer()
   {
   /* Add code to ask user to input a name and a position,
   * then use the data to add a new Player object into the
   * players attribute.
   *
   * There is no need for any input validations.
   *
   * Hints:
   * - use a Scanner to get user inputs
   * - create a new Player object
   * - use the add() method of the ArrayList class to add it into the list
   */
  
       Scanner scan = new Scanner(System.in);
       System.out.println("Adding player.....");
       System.out.println("Enter name: ");
       String name = scan.nextLine();
       System.out.println("Enter position: ");
       int position = scan.nextInt();
       Player p = new Player(name, position);
       players.add(p);
   }

   // Q.4(c) for Week 8
   public int findPlayer(String name)
   {
   int index = -1;
  
   /* Add code to allow user to search for an existing Player object
   * in players. The parameter is a string representing the name
   * of the Player object to search. The return value is the index
   * where the object is found, or -1 if the object is not found.
   *
   * Assume there are no duplate names in the list.
   *
   * Hints:
   * - use a loop to search through the ArrayList
   * - compare the given name to each Player's name in the list
   * - use the indexOf() method to return the required index
   */
       for(Player p: players) {
           if(p.name.contentEquals(name))
               index = players.indexOf(p);
       }
      
       return index;
   }

   // Q.4(d) for Week 8
   public boolean updatePlayerName(int index)
   {
   boolean success = false;
  
   /* Add code to allow user to modify an existing Player object
   * in players. The parameter is the index to the Player object
   * in the ArrayList. Your code should first check if the given
   * index is within the correct range (between 0-max, where max
   * if the ize of the list. If the index is not valid,
   * or the player list is empty,
   * print out an error message, otherwise ask the user to input
   * a new name and update the Player object with that name.
   * If the update operation is successful, return true (otherwise
   * return false).
   *
   * Hints:
   * - check if index is valid and list is not empty
   * - if yes, use it to get at the correct Player in the list
   * - update the Player's name
   * - return the appropriate boolean result
   */
       //If valid index
       if(index>=0 && index<players.size()) {
           System.out.println("Updating player name at index " + index);
           Scanner scan = new Scanner(System.in);
           System.out.println("Enter name: ");
           String name = scan.nextLine();
           //Create new player with new name and old position
           Player p = new Player(name, players.get(index).position);
           //Remove old object at the specified index
           players.remove(index);
           //Add updated player at the index
           players.add(index, p);
           success = true;
       } else {
           System.out.println("Error updating player name. ");
       }
  
       return success;
   }
  
   // *** Pre-tute Task 1 for Week 9 ***
   public boolean removePlayer(String name)
   {
   boolean success = false;
  
   /* Add code to allow user to remove an existing Player object
   * in players. The parameter is the name of the Player object
   * to be removed. Your code should first check if th object
   * with that name does exist.
   *
   * Your code *MUST* make a call to the findPlayer() method you
   * wrote in Q.4(c) above.
   *
   * If the remove operation is successful, return true (otherwise


   * Hints:
   * - use the findPlayer() method to find the position of the object
   * - remove the Player if it exists
   * - return the appropriate boolean result
   */
  
       int index = findPlayer(name);
       //If object found in players list
       if(index>0) {
           players.remove(index);
           success = true;
       }
  
   return success;
   }
  
   // *** Pre-tute Task 2 for Week 9 ***
   public boolean updatePlayerName(String oldName, String newName)
   {
   boolean success = false;
  
   /* Add code to allow user to modify an existing Player object
   * in players. This time the method takes 2 parameters: oldName
   * is the name for an Player object to be searched for, newName
   * is the name to update the object with. Your code should first
   * check if the object with the oldName does exist.
   *
   * Your code *MUST* make a call to the findPlayer() method you
   * wrote in Q.4(c) above.
   *
   * If the update operation is successful, return true (otherwise
   * return false, and print a simple error message).
   *
   * Hints:
   * - use the findPlayer() method to find the position of the object
   * - update the Player's name with the given parameter (newName)
   * - return the appropriate boolean result
   */
  
       int index = findPlayer(oldName);
       if(index>=0) {
           //Create new player with new name
           Player p = new Player(newName, players.get(index).position);
           //Remove old player
           players.remove(index);
           //Add new player at that index
           players.add(index, p);
           success = true;
       }else
           System.out.println("Error updating old player name with new name.");
       return success;
   }
   //Test of above methods
   public static void main(String[] args) {
       ListOfPlayers lop = new ListOfPlayers();
       lop.add3Players();
       lop.displayPlayers();
       lop.addPlayer();
       lop.clearPlayers();
       lop.add3Players();
       lop.updatePlayerName(0);
       lop.displayPlayers();
       lop.removePlayer("Robert");
       lop.updatePlayerName("Robert", "David");
   }
}

Player.java

public class Player {
   String name;
   int position;
   Player(String s, int r){
       name = s;
       position = r;
   }
   public void display() {
       System.out.println("Name: " + name + " Position: " + position);
   }
}

I've addes some simple statements in main method to test. You can add more statements in main to test and understand, although I've included everything in comments.


Related Solutions

Please add comments to this code! JAVA Code: import java.text.NumberFormat; public class Item {    private...
Please add comments to this code! JAVA Code: import java.text.NumberFormat; public class Item {    private String name;    private double price;    private int bulkQuantity;    private double bulkPrice;    /***    *    * @param name    * @param price    * @param bulkQuantity    * @param bulkPrice    */    public Item(String name, double price, int bulkQuantity, double bulkPrice) {        this.name = name;        this.price = price;        this.bulkQuantity = bulkQuantity;        this.bulkPrice = bulkPrice;   ...
Please add comments to this code! JAVA code: import java.util.ArrayList; public class ShoppingCart { private final...
Please add comments to this code! JAVA code: import java.util.ArrayList; public class ShoppingCart { private final ArrayList<ItemOrder> itemOrder;    private double total = 0;    private double discount = 0;    ShoppingCart() {        itemOrder = new ArrayList<>();        total = 0;    }    public void setDiscount(boolean selected) {        if (selected) {            discount = total * .1;        }    }    public double getTotal() {        total = 0;        itemOrder.forEach((order) -> {            total +=...
Can you please add comments to this code? JAVA Code: import java.util.ArrayList; public class Catalog {...
Can you please add comments to this code? JAVA Code: import java.util.ArrayList; public class Catalog { String catalog_name; ArrayList<Item> list; Catalog(String cs_Gift_Catalog) { list=new ArrayList<>(); catalog_name=cs_Gift_Catalog; } String getName() { int size() { return list.size(); } Item get(int i) { return list.get(i); } void add(Item item) { list.add(item); } } Thanks!
JAVA ONLY - Complete the code import java.util.Scanner; /** * This program will use the HouseListing...
JAVA ONLY - Complete the code import java.util.Scanner; /** * This program will use the HouseListing class and display a list of * houses sorted by the house's listing number * * Complete the code below the numbered comments, 1 - 4. DO NOT CHANGE the * pre-written code * @author * */ public class HouseListingDemo { public static void main(String[] args) { Scanner scan = new Scanner(System.in); HouseListing[] list; String listNumber, listDesc; int count = 0; double listPrice; String...
In Java please Cipher.java: /* * Fix me */ import java.util.Scanner; import java.io.PrintWriter; import java.io.File; import...
In Java please Cipher.java: /* * Fix me */ import java.util.Scanner; import java.io.PrintWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; public class Cipher { public static final int NUM_LETTERS = 26; public static final int ENCODE = 1; public static final int DECODE = 2; public static void main(String[] args) /* FIX ME */ throws Exception { // letters String alphabet = "abcdefghijklmnopqrstuvwxyz"; // Check args length, if error, print usage message and exit if (args.length != 3) { System.out.println("Usage:\n"); System.out.println("java...
In Java: Complete the following methods in the template by adhering to the comments: // TO...
In Java: Complete the following methods in the template by adhering to the comments: // TO DO: add your implementation and JavaDoc public class BetterArray<T> { private static final int DEFAULT_CAPACITY = 2; //default initial capacity / minimum capacity private T[] data; //underlying array, you MUST use this for full credit // ADD MORE PRIVATE MEMBERS HERE IF NEEDED! @SuppressWarnings("unchecked") public BetterArray() { //constructor //initial capacity of the array should be DEFAULT_CAPACITY } @SuppressWarnings("unchecked") public BetterArray(int initialCapacity) { // constructor...
fix this code in python and show me the output. do not change the code import...
fix this code in python and show me the output. do not change the code import random #variables and constants MAX_ROLLS = 5 MAX_DICE_VAL = 6 #declare a list of roll types ROLLS_TYPES = [ "Junk" , "Pair" , "3 of a kind" , "5 of a kind" ] #set this to the value MAX_ROLLS pdice = [0,0,0,0,0] cdice = [0,0,0,0,0] #set this to the value MAX_DICE_VAL pdice = [0,0,0,0,0,0] cdice = [0,0,0,0,0,0] #INPUT - get the dice rolls i...
Can someone please convert this java code to C code? import java.util.LinkedList; import java.util.List; public class...
Can someone please convert this java code to C code? import java.util.LinkedList; import java.util.List; public class Phase1 { /* Translates the MAL instruction to 1-3 TAL instructions * and returns the TAL instructions in a list * * mals: input program as a list of Instruction objects * * returns a list of TAL instructions (should be same size or longer than input list) */ public static List<Instruction> temp = new LinkedList<>(); public static List<Instruction> mal_to_tal(List<Instruction> mals) { for (int...
UML Diagram for this java code //java code import java.util.*; class Message { private String sentence;...
UML Diagram for this java code //java code import java.util.*; class Message { private String sentence; Message() { sentence=""; } Message(String text) { setSentence(text); } void setSentence(String text) { sentence=text; } String getSentence() { return sentence; } int getVowels() { int count=0; for(int i=0;i<sentence.length();i++) { char ch=sentence.charAt(i); if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' || ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U') { count=count+1; } } return count; } int getConsonants() { int count=0; for(int i=0;i<sentence.length();i++)...
Please convert this code written in Python to Java: import string import random #function to add...
Please convert this code written in Python to Java: import string import random #function to add letters def add_letters(number,phrase):    #variable to store encoded word    encode = ""       #for each letter in phrase    for s in phrase:        #adding each letter to encode        encode = encode + s        for i in range(number):            #adding specified number of random letters adding to encode            encode = encode +...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT