Data Structure and Algorithms Assignment

Question 1

In this exercise we’ll be using a combination of things we’ve worked on before, but now starting almost from scratch. No individual element here is new, so read the instructions carefully and break the task down into steps.

In the skeleton you are given a class Sequence with very little code in it. It starts with an array called sequence, and that’s about it.

Below the indicated comment you need to do the following (you may want to think about the order):

  • Create a standard main method. In the main method you need to:
    • Create a Scanner object to be used to read things in
    • Print a prompt to "Enter the first double: ", without a new line after it.
    • Read a double in from the user and store it as the first element of sequence.
    • Print a prompt to "Enter the second double: ", without a new line after it.
    • Read a double in from the user and store it as the second element of sequence.
    • Calculate a third double which is the seconddouble divided by the first double, all multiplied by the second double.
    • Store this third double as the third element of sequence.
    • Print "The first element was <x>, the second element was <y>, so the third element is <z>." where <x>, <y> and <z> are replaced by the values of the first, second and third doubles respectively.

Remember that computers aren’t clever, so note the formatting and punctuation, especially in the feedback of the tests.

Note also that part of the task is to use the array sequence. Although you can print out the correct things without it, you cannot pass the task.

As an example, you have also been given the class AreaOfRectangle, you do not need to change anything, it is just

Starter Code Question one

import java.util.Scanner;

public class Sequence {

    static double [] sequence = {0, 0, 0};

    // DO NOT CHANGE ANYTHING ABOVE THIS COMMENT LINE

    //Create a main method

    //Create a Scanner

    //Prompt the user as per the description and read in a double.

    //Prompt the user as per the description and read in another double.

    //Calculate the third double.

    //Print out the message about the sequence values.

    //Don’t forget to put a closing brace at the end of the main method.

}

Question 2

In this exercise we’ll be using a slightly different combination of things we’ve worked on before, starting from scratch again. No individual element here is new, so read the instructions carefully and break the task down into steps.

In the skeleton you are given a class ThreeNumbers which starts with an array called num, and little else.

Below the indicated comment you need to do the following (you may want to think about the order):

  • Create a standard main method. In the main method you need to:
    • Create a Scanner object to be used to read things in
    • Print a prompt to "Enter the first number: ", without a new line after it.
    • Read an int in from the user and store it as the first element of num.
    • Print a prompt to "Enter the second number: ", without a new line after it.
    • Read an int in from the user and store it as the second element of num.
    • Print a prompt to "Enter the third number: ", without a new line after it.
    • Read an int in from the user and store it as the third element of num.
    • Print "The sum of the three numbers is <sum>.", with a new line after it, where <sum> is replaced by the actual sum of the elements of num.
    • Print "The average of the three numbers is <avg>.", with a new line after it, where <avg> is replaced by the actual average (rounded down, so you can use integer division) of the the elements of num.

Remember that computers aren’t clever, so note the formatting and punctuation, especially in the feedback of the tests.

Note also that part of the task is to use the array num. Although you can print out the correct things without it, you cannot pass the task.

Question 2 Starter Code:

import java.util.Scanner;

/*

class ThreeNumbers

    static int [] num = {0, 0, 0};

    // DO NOT CHANGE ANYTHING ABOVE THIS COMMENT LINE

    //Create a main method

    //Create a Scanner

    //Prompt the user as per the description and read in an int.

    //Prompt the user as per the description and read in another int.

    //Prompt the user as per the description and read in the third int.

    //Calculate the sum.

    //Calculate the average.

    //Print out the messages about the sum and average.

    //Don’t forget to put a closing brace at the end of the main method.

}

Question 3

In this exercise the goal is to implement the Bubble Sort algorithm on a small array. If you are comfortable with loops and arrays, you can solve this by implementing the full algorithms. If you are not, you can “unroll” the loop and implement each step by hand by hard coding each pass through the array as a sequence of explicit checks and potential swaps.

The skeleton contains two methods:

  1. A main method which will allow you to do your own testing, and give a working example.
  2. A bubbleSort method where you’ll do the actual implementation of the sorting algorithm.

The bubbleSort method takes in an int[] called data. This is the array that you are to sort. You are guaranteed for this exercise that data will have length 4. At the end of the method you should return data;. This line has already been added, so you can just leave it as is.

For the tests to ensure you are correctly implementing a Bubble Sort (and not some other sort, or using a library), you must print out the array using printArray(data) every time you swap elements in the array. You should not print it out any other time in the bubbleSort method.

Question 3 – Starter Code

import java.util.Arrays;

public class BubbleSort {

    //Don’t touch this method!

    private static void printArray(int[] a) {

        System.out.println(Arrays.toString(a));

    }

    //Complete this method.

    public static int[] bubbleSort(int[] data) {

        //Implement a Bubble Sort on data here!

        return data;

    }

    //You can mess around in the main method

    //as you wish. As long as it compiles,

    //it won’t affect the testing.

    public static void main(String[] args) {

        int[] testData = {45, 93, 33, 55};

        System.out.println(“Sorting.”);

        testData = bubbleSort(testData);

        System.out.println(“After sorting the array is: “);

        printArray(testData);

    }

}

Question 4 :

In this exercise the goal is to implement the Selection Sort algorithm on a small array, in a similar manner to the Bubble Sort required exercise. If you are comfortable with loops and arrays, you can solve this by implementing the full algorithms. If you are not, you can “unroll” the loop and implement each step by hand by hard coding each pass through the array as a sequence of explicit checks and potential swaps.

The skeleton contains two methods:

  1. A main method which will allow you to do your own testing, and give a working example.
  2. A selectionSort method where you’ll do the actual implementation of the sorting algorithm.

The selectionSort method takes in an int[] called data. This is the array that you are to sort. You are guaranteed for this exercise that data will have length 4. At the end of the method you should return data;. This line has already been added, so you can just leave it as is.

For the tests to ensure you are correctly implementing a Selection Sort (and not some other sort, or using a library), you must print out the array using printArray(data) every time you swap elements in the array. You should not print it out any other time in the selectionSort method. For consistency in which version of Selection Sort is implemented:

  1. Stop the sort once the unsorted area is only one element.
  2. Don’t swap if the minimum element is the first element in the unsorted area (so no print out in this case).

Question 4 Starter Code

import java.util.Arrays;

public class SelectionSort {

    //Don’t touch this method!

    private static void printArray(int[] a) {

        System.out.println(Arrays.toString(a));

    }

    //Complete this method.

    public static int[] selectionSort(int[] data) {

        //Implement a Selection Sort on data here!

        return data;

    }

    //You can mess around in the main method

    //as you wish. As long as it compiles,

    //it won’t affect the testing.

    public static void main(String[] args) {

        int[] testData = {45, 93, 33, 55};

        System.out.println(“Sorting.”);

        testData = selectionSort(testData);

        System.out.println(“After sorting the array is: “);

        printArray(testData);

    }

}

Question 5

This exercise is similar to the “Calling Methods” exercise, but flipped. Here we will be filling out methods so that they function as specified. The code here is also a little “simpler”, in that it is contained in a single class, and everything is static, so we don’t need to deal with creating objects just yet.

In the skeleton you have a class called BankAccountStatic. The class has three data members accountNumber, accountName and balance. You do not need to do anything to these declarations.

It contains two completed methods: a main method which runs at least one example of each method, you can change the main as much as you like, as long as it compiles, it will not affect the marking; a method called withdraw, this method should serve as an example for the methods you have to complete, although the methods you have to complete are typically much simpler, do not change this method.

Your task is to complete these six methods:

  • getAccountNumber
  • setAccountNumber
  • getAccountName
  • setAccountName
  • getBalance
  • deposit

Each of this represents a method that either accesses or changes one of the three data members, as suggested by the name. You should read the comment block associated with each method, as it describes what needs to be complete for each method.

Question 5 Starter Code

/**

 * This “BankAccount” class is a simple introduction to

 * methods and variables / fields / private data members.

 *

/*

 * HINT: You should NOT need to memorise much to complete

 *       this skeleton.  The type of the variables

 *       “accountNumber”, “accountName” and “balance”

 *       (i.e. int, String and double respectively)

 *       provide useful information.

 */

public class BankAccountStatic

{

  /*

   * The variables follow. These are also

   * called “fields” or “?”private data members”.

   */

   private static int accountNumber = 0;

   private static String accountName = “no name”;

   private static double balance; // eg. 1.27 means $1.27

   public static void main(String[] args) {

      System.out.println(“The initial value for account number is ” + accountNumber + “. Look at line 24.”);

      System.out.println(“The initial value for account name is ” + accountName + “. Look at line 26.”);

      System.out.println(“The initial value for balance is ” + balance + “. Look at line 28.”);

      BankAccountStatic.setAccountNumber(12345678);

      BankAccountStatic.setAccountName(“Samantha”);

      //the above two lines should update the values stored in accountNumber and accountName to the given value. Let’s test it:

      System.out.println(“The new account number is 12345678. Your program’s new account number is ” + accountNumber +”. If these two numbers don’t match then something is not right…”);

      System.out.println(“The new account name is Samantha. Your program’s new account name is ” + accountName+”. If these two names don’t match then something is not right…”);

      //lets put some money in the account

      BankAccountStatic.deposit(3.70);

      //the new balance should be 3.70. Let’s check it:

      System.out.println(“New balance should be 3.70. Your program’s new balance is ” + balance+”. If these two numbers don’t match then something is not right…”);

      //let’s put some more money in our bank account:

      BankAccountStatic.deposit(100.00);

      //the new balance should be 103.70. Let’s check it:

      System.out.println(“New balance should be 103.70. Your program’s new balance is ” + balance+”. If these two numbers don’t match then something is not right…”);

      //let’s withdraw some money now. the new balance should be 93.20. Let’s check it:

      System.out.println(“After this line, the new balance should be 93.20. Your program’s balance after calling withdraw(10.50) is ” + BankAccountStatic.withdraw(10.50) + “. If these two numbers don’t match then something is not right…”);

                              //let’s attempt to withdraw more than what we have in the account. The result of print statement should be zero:

      System.out.println(“Attempting to withdraw 1000.00 dollars from this bank accoutn should return a -1.0. Your program’s return value after calling withdraw(1000.00) is ” + BankAccountStatic.withdraw(1000.00) + “. If these two numbers don’t match then something is not right…”);

               }

   /**

    * This method needs to be completed. It needs:

    * – a proper return type

    * – a proper list of parameters (maybe empty)

    * – code to actually do what it should

    */

    public static returntype getAccountNumber(parametersIfAny)      

    {

        add whatever code is required here in the method body

    }

   /**

    * This method needs to be completed. It needs:

    * – a proper return type

    * – a proper list of parameters (maybe empty)

    * – code to actually do what it should

    */

    public static returntype setAccountNumber(parametersIfAny)

    {

       add whatever code is required here in the method body

    }

   /**

    * This method needs to be completed. It needs:

    * – a proper return type

    * – a proper list of parameters (maybe empty)

    * – code to actually do what it should

    */

    public static returntype getAccountName(parametersIfAny)

    {

       add whatever code is required here in the method body

    }

   /**

    * This method needs to be completed. It needs:

    * – a proper return type

    * – a proper list of parameters (maybe empty)

    * – code to actually do what it should

    */

    public static returntype setAccountName(parametersIfAny)

    {

       add whatever code is required here in the method body

    }

   /**

    * This method needs to be completed. It needs:

    * – a proper return type

    * – a proper list of parameters (maybe empty)

    * – code to actually do what it should

    */

    public static double getBalance(parametersIfAny)

    {

        add whatever code is required here in the method body

    }

   /**

    * This method needs to be completed. It needs:

    * – a proper return type

    * – a proper list of parameters (maybe empty)

    * – code to actually do what it should

    */

    public static returntype deposit(parametersIfAny) 

    {

        add whatever code is required here in the method body

    }

   /**

    * @param   amount  To be subtracted from the balance

    *

    * @return  the updated account balance or -1.0 if the withdrawal is refused

    *

    * The withdrawal is refused when the withdrawal would

    * have resulted in a negative balance.

    *

    * Note: This method “withdraw” has been provided in

    *       its entirety. You do NOT have to make any

    *       changes to it.

    */

    public static double withdraw(double amount)

    { 

       if ( balance >= amount )

       {

          balance = balance – amount;

          return balance;

       }

       else

          return -1.0;

    }

} // class BankAccountStatic

Question 6

Here will we again build some methods, but in a slightly different context, to help build the programming links between the code and your conception of it, rather than just understanding how a bank account should work.

In the skeleton you have a class called SummerStatic. The class has two data members sum and count. You do not need to do anything to these declarations. The purpose of the class is to receive numbers one by one, and update the current sum and count, and thus be able to report on the sum, average and count. The sequence can also be reset if desired.

It contains one completed method: a main method which runs at least one example of each method, you can change the main as much as you like, as long as it compiles, it will not affect the marking.

Your task is to complete the following six methods:

  1. putNumber
  2. reset
  3. a different reset
  4. getSum
  5. getCount
  6. getAverage

You should read the description of each method in the associated comment block carefully as it describes the purpose of each method, and what needs to be completed for the method

Question 6 Starter Code

/**

 * This “Summer” class is a simple introduction to

 * methods and variables / fields / private data members.

 *

public class SummerStatic

{

  /*

   * The variables follow. These are also

   * called “fields” or “private data members”.

   */

   private static int sum;   // sum of all integers received

   private static int count; // number of integers received

   public static void main(String [] args)

   {

      /*

       * Note: This method “main” has been provided in

       * its entirety. You do NOT have to make any

       * changes to it.

       *

       * You could use this “main” method to test your code.

       */

       System.out.println(“First we call reset so that th evalues of sum and count are set to zero.”);

       reset();

       System.out.println(“Now we assign numbers 17 and 1.”);

       putNumber(17);

       putNumber(1);

       System.out.println(“Now we call getCount, getSum and getAverage in three print statements to check the values.”);

       System.out.println(“count should be 2, sum should be 18 and average should be 9.00:”);

       System.out.println(“Now we call getCount, getSum and getAverage in three print statements to check the values.”);

       System.out.println(“”);

       System.out.println(“”);

       System.out.print(“count = ” + getCount() + ” “);

       System.out.print(“sum = ” + getSum() + ” “);

       System.out.println(“average = ” + getAverage());

       System.out.println(“”);

       System.out.println(“”);

       System.out.println(“”);

       System.out.println(“”);

       System.out.println(“”);

       // Repeat for a second set of numbers

       System.out.println(“We run the program again, this time we start by calling reset(3)”);

       reset(3);

       System.out.println(“Now we assign numbers 5 and 7.”);

       putNumber(5);

       putNumber(7);

       System.out.println(“Now we call getCount, getSum and getAverage in three print statements to check the values.”);

       System.out.println(“count should be 3, sum should be 15 and average should be 5.00:”);

       System.out.println(“”);

       System.out.println(“”);

       System.out.print(“count = ” + getCount() + ” “);

       System.out.print(“sum = ” + getSum() + ” “);

       System.out.println(“average = ” + getAverage());

   } // method main

    /**

    * Receives and processes a new number in the series

    * This method needs to be completed. It needs:

    * – a proper return type

    * – a proper list of parameters (maybe empty)

    * – code to actually do what it should

    */

    public static returntype putNumber(parametersIfAny)

    {

        add whatever code is required here in the method body

    }

    /**

    * Resets so all numbers previously forgotten. This is

    * dangerous since average is now undefined.

    * This method needs to be completed. It needs:

    * – a proper return type

    * – a proper list of parameters (maybe empty)

    * – code to actually do what it should    

    */

    public static returntype reset(parametersIfAny)

    {

        add whatever code is required here in the method body

    }

    /**

    * Resets with the first number of a new series. This is

    * safer reset since the average remains defined.

    * This method needs to be completed. It needs:

    * – a proper return type

    * – a proper list of parameters (maybe empty)

    * – code to actually do what it should

    */

    public static returntype reset(parametersIfAny)

    {

        add whatever code is required here in the method body

    }

    /**

    * This method needs to be completed. It needs:

    * – a proper return type

    * – a proper list of parameters (maybe empty)

    * – code to actually do what it should

    */

    public static returntype getSum(parametersIfAny)

    {

        add whatever code is required here in the method body

    }   

    /**

    * This method needs to be completed. It needs:

    * – a proper return type

    * – a proper list of parameters (maybe empty)

    * – code to actually do what it should

    */

    public static returntype getCount(parametersIfAny)

    {

        add whatever code is required here in the method body

    }

    /**

    * This method needs to be completed. It needs:

    * – a proper return type

    * – a proper list of parameters (maybe empty)

    */

    public static returntype getAverage(parametersIfAny)

    {

     /*

      * Note: This body of this method “getAverage” has

      * been provided in its entirety. You do NOT have

      * to make any changes to it.

     */

        return (

                 (double) sum  /  (double) count

               );

    }

} // class SummerStatic

Question 7

This exercise builds on the static version of the same exercise from last week. The idea is basically the same, we have series of methods to complete, but this time they are not static – i.e. they relate to object-level data.

This means that to actually use these methods and the data members they (should) access, an object needs to be created. As before, this part has actually already been done in the main method, and it is useful to observe the differences between this week and last’s week’s required exercises.

In many ways, the result of this exercise will look very similar to the static version, but now we can have several BankAccounts, with differing data.

To complete it, you have to provide return types, parameter lists and code for the following methods:

  • setInterestRate
  • getInterestRate
  • toString

You also have to complete two constructors. If you are unsure what a constructor is, or the syntax, check the Classes and Objects lesson, or talk to the teaching staff.

Question 7 Starter Code          

/**

 * This Object-Oriented” version of the “BankAccount” class

 * is a simple introduction to Constructors /

 * private data members / static vs. not static / and the

 * “toString” method.

 *

 * SKELETON FOR LAB TEST.

 */

public class BankAccountOO {

    public static double interestRate = 0.0;

    // Note: the interest rate is “static”. That is, all

    //       bank accounts have the same interest rate.

    /*

     * The instance variables follow (i.e. not static). These

     * are also called “fields” or “private data members”.

     */

    public final int accountNumber;

    public String accountName;

    public double balance; // e.g. 1.27 means $1.27

    public static void main (String[] args) {

        BankAccountOO.setInterestRate(7.50);

        System.out.println(“(Interest rate should be 7.50) Interest rate is ” + BankAccountOO.getInterestRate() + “.”);

        BankAccountOO bankaccountoo = new BankAccountOO(99998888,”Jack”);

        System.out.println(“So we created an account for Jack with zero dollars in his bank account under the account number 99998888.”);

        System.out.println(“”);

        System.out.println(“”);

        System.out.println(“For the object created, the account number is: ” + bankaccountoo.accountNumber);

        System.out.println(“For the object created, the account name is: ” + bankaccountoo.accountName);

        System.out.println(“For the object created, the balance is: ” + bankaccountoo.balance);

        System.out.println(“”);

        System.out.println(“”);

        System.out.println(“”);

        System.out.println(“Now we use the constructor which takes three argumants including name, number and initial balance:”);

        BankAccountOO bankaccountoo2 = new BankAccountOO(12345678,”Jane”,1000.99);

        System.out.println(“So we created an account for Jane with 1000.99 dollars in her bank account under the account number 12345678”);

        System.out.println(“”);

        System.out.println(“”);

        System.out.println(“For the second object created, the account number is: ” + bankaccountoo2.accountNumber);

        System.out.println(“For the second object created, the account name is: ” + bankaccountoo2.accountName);

        System.out.println(“For the second object created, the balance is: ” + bankaccountoo2.balance);

        System.out.println(“”);

        System.out.println(“”);

        System.out.println(“”);

        System.out.println(“Now we use the method toString to print it all in the same line”);

        System.out.println(“First object: ” + bankaccountoo.toString());

        System.out.println(“Second object: ” + bankaccountoo2.toString());

        System.out.println(“”);

        System.out.println(“”);

        System.out.println(“Testing withdraw method on Jane’s account: Jane’s new balance after we withdraw 100.00 is ” + bankaccountoo2.withdraw(100.00));

    } 

    /**

    *   The constructors now follow

    */

    /**

     * @param    num  number for the account

     * @param    name name of the account

     */    

    public returnTypeIfAny nameOfConstructor(parametersIfAny) {

        add whatever code is required in the constructor body

    }

    /**

     * @param    num    number for the account

     * @param    name   name of the account

     * @param    bal    opening balance

     */

    public returnTypeIfAny nameOfConstructor(parametersIfAny) {

        add whatever code is required in the constructor body

    }

    /*

     * A number of the methods from the “static” version

     * have been left out of this object-oriented version

     * because you’ve already done that once.

     *

     * Most of those methods would appear in a complete

     * version of this object-oriented version of the

     * class, with the *ONLY* change being that the reserved

     * word “static” would be deleted from the method

     * header.

     *

     * The method setAccountNumber() would definitely NOT

     * be copied across from the static version to this

     * object-oriented version. That’s because each object

     * (i.e. instance of BankAccount) represents a unique

     * bank account. The account number set up by the

     * constructor should never change again.

     *

     * The method setAccountName() MIGHT be copied across. 

     * That’s a business decision.  Some banks might allow

     * a customer to change their name.  Other banks might

     * only allow a name change by creating a new account. 

     * If the account name cannot be changed, then the

     * declaration of private data member “accountName”

     * should have the reserved word “final” added.

     *

     * The method withdraw() has been copied across

     * because:

     * (1) it was provided in its entirety in the

     *     “static” version of the class,

     * (2) to provide an example that “static” is dropped

     *     from the header,

     * (3) to provide a hint as to what changes might be

     *     needed for the other, incomplete methods.

     */

    /**

     * The withdrawal should be refused if the withdrawal

     * would result in a negative balance.

     *

     * @param   amount  The amount to be withdrawn

     *

     * @return  new balance or -1.0 if withdrawal refused

     */

    public returntype withdraw(double amount) { 

        if ( balance >= amount ) {

            balance = balance – amount;

            return balance;

        }

        else

            return -1.0;

    }

    /**

     * Note that this is a static method. So a change to the

     * interest rate changes the interest rate for all objects

     * of this class.

     *

     * @param   newInterest    The new interest rate

     */

    public static returntype setInterestRate(parametersIfAny) {

        add whatever code is required here in the method body

    }

    /**

     * Note that this is a static method.

     *

     * @return   The interest rate

     */

    public static returntype getInterestRate(parametersIfAny) {

        add whatever code is required here in the method body

    }

    /**

     * It is common practise to supply a “toString” method

     * in an object-oriented class.  In fact, if you don’t

     * explicitly supply such a method, Java produces an

     * implicit, simplistic “toString” method which produces

     * a String like “BankAccountOO@1edd1f0”. The word before

     * the “@” is the name of the class. The hexadecimal

     * number after the “@” is called the objects “hash code”.

     * 

     * Note: Method “toString” method is NOT “static”. It

     * can’t be static, since the values in the data members

     * may vary between objects of this class.

     *

     *@return   The state of this “class instance” or “object” 

     */

    public returntype toString(parametersIfAny) {

        return “accountNumber = ”  + accountNumber +

               ” accountName = ”   + accountName   +

               ” balance = ”       + balance;

    }

} // class BankAccountOO

Question 8

As with the bank account exercises, here we revisit the Summer exercise and change from using static variables and methods to a mixture of static and non-static ones. As before, the immediate consequences to the written code are not dramatic, but the implied use is. Once this is complete, we can create multiple Summers, to keep as many sums as we care to, rather than only being able to retain a single sum in the static case. This exercise also includes a static variable and related static method that shows a more natural use of class level static data.

Your task here is to complete two constructors, and the methods getNumSummers and toString

Question 8 Starter Code

/**

 * This Object-Oriented version of the “Summer” class

 * is a simple introduction to constructors /

 * private data members / static vs. not static / and the

 * “toString” method.

 *

 * SKELETON FOR LAB TEST.

 *

 *

 */

public class SummerOO

{

    static int numSummers = 0;

    // The above variable is used to count the number of

    // instances of the class SummerOO that have been created.

    // (i.e. the number of objects that have been created.)

    //

    // Note: “numSummers” is declared as “static”. It is a

    //       variable that belongs to the class, not an

    //       individual object.

    /*

     * The instance variables follow (i.e. not static). These

     * are also called “fields” or “data members”.

     * Each object has its own copy of these variables.

     */

    int sum;   // sum of all integers received

    int count; // number of integers received

    /**

     * The constructors now follow. There are two constructors.

     * Both constructors have the same name, since all

     * constructors always have the same name as the class.

     * The constructors are distinguishable because one of the

     * constructors requires zero parameters while the other

     * constructor requires a single integer parameter.

     */

    /**

     * This is a “dangerous” constructor, since the average is

     * undefined when the object is created.

     *

     * This constructor and the method reset()

     * are similar. The differences are that:

     * (1) The constructor can only be used once, when the

     *     object is created.

     * (2) The method reset() can’t create an object, but it can

     *     be used whenever we like, as many times as we like,

     *     after the object has been created.

     */

    public returnTypeIfAny nameOfConstructor()

    {

        add whatever code is required in the constructor body

    }

    /**

     * This is a safer constructor, since the average is

     * well defined when the object is created.

     *

     * This constructor and the method reset(int firstNumber)

     * are similar. The differences are that:

     * (1) The constructor can only be used once, when the

     *     object is created.

     * (2) The method reset() can’t create an object, but can

     *     be used whenever we like, as many times as we like,

     *     after the object has been created.

     *

     * @param   firstNumber The first number of a series

     */

    public returnTypeIfAny nameOfConstructor(parameter)

    {

        add whatever code is required in the constructor body

    }

    /**

     * Receives and processes a new number in the series.

     *

     * NOTE TO STUDENTS: When studying this code, experiment

     * by adding “static” into “public void putNumber”.

     * When you compile, you’ll get an error message …

     *

     * “non-static variable sum cannot be referenced from a

     * static context”.

     *

     * In other words a “static” method (which belongs to the

     * class, not an individuaual object), can’t access the

     * variables in an object. This is for two reasons:

     * (1) If we haven’t created ANY objects yet, then there is

     *     no variable “sum” to access!

     * (2) If multiple objects (“instances”) of this

     *     class exist, then there are multiple versions of

     *     the “sum” variable, one version of “sum” in each

     *     object. The static method (which belongs to the

     *     class) cannot choose from the many versions of “sum”.

     *  The same applies to the variable “count”. The error

     *  message singled out “sum” because it occured before

     *  “count”.

     *

     * @param  newNumber   a new number in the series

     */

    public /* not static! */ void putNumber(int newNumber)

    {

        // This method is complete. No changes are required to

        // “putNumber” in the lab test.

        sum = sum + newNumber; // could write “sum += newNumber”

        count = count + 1;     // could write “++count”

    }

    /*

     * A number of the methods from the “static” version

     * have been left out of this object-oriented version

     * because you’ve already done that.

     *

     * All those methods would appear in a complete

     * version of this object-oriented version of the

     * class, with the *ONLY* change being that the reserved

     * word “static” would be deleted from the method

     * header.

     *

     * The method putNumber() has been copied across to support

     * the experiment of adding “static” to its header,

     */

    /**

     * Note that this is a static method.

     *

     * @return  The number of objects that have been created.

     */

    public static returntype getNumSummers(parametersIfAny)

    {

        add whatever code is required here in the method body

    }

    /**

     * It is common practise to supply a “toString” method

     * in an object-oriented class.  In fact, if you don’t

     * explicitly supply such a method, Java produces an

     * implicit, simplistic “toString” method which produces

     * a String like “SummerOO@1edd1f0”. The word before

     * the “@” is the name of the class. The hexadecimal

     * number after the “@” is called the objects “hash code”.

     * 

     * Note: Method “toString” method is NOT “static”. It

     * can’t be static, since the values in the data members

     * may vary between objects of this class.

     *

     *@return   The state of this “class instance” / “object” 

     */

    public returntype toString(parametersIfAny)

    {

        return “sum = ”  +  sum  +  ” count = ”  +  count;

    }

    /**

     * The main method is already complete, and you

     * don’t need to change anything, but it won’t

     * hurt anything if you do, as long as it still

     * compiles.

     */

    public static void main(String [] args)

    {

        SummerOO summer1 = new SummerOO();

        // the above line used the zero parameter constructor.

        summer1.putNumber(17);

        summer1.putNumber(1);

        System.out.println(summer1.toString());

        // in the above line, the “.toString()” can be omitted,

        // to give just …

        //                  System.out.println(summer1);

        //

        // When the name of an object is given where a String

        // is required (and println requires a String), Java

        // automatically calls the “toString()” method of the

        // object.

        // Repeat for a second set of numbers

        System.out.println();

        SummerOO summer2 = new SummerOO(3);

        // above line used the constructor that takes a parameter

        summer2.putNumber(5);

        summer2.putNumber(7);

        System.out.println(summer2);

        // in the above line, Java automatically calls the

        // “toString()” method of the “summer2” object.

    } // method main

} // class SummerOO

Question 9

The basic idea of a list in most programming languages is that of an array, but where elements can be added or removed (i.e. it can be resized).

In this exercise we’re going to take a step towards that idea and build a simplified version of a list backed by an array as the actually storage. That is, the class will store an array internally, but present a list-like interface to the outside world. The list will store ints, to help keep things simple.

The skeleton starts with the basic class defined, and a single data member data of type int[]. It’s public only to simplify testing, and final to prevent one particular misstep in some of the tasks.

The tasks are then to complete the methods in the class, as given by their method signatures (more detail is given in the comments in the class as well):

  1. MyArrayList() – A constructor which will initialise the array and any other data members you add. The array should have length 6. Note that this is not the same as the size of the list, it just defines the maximum size. The list starts empty. The values stored in unused portions of the array are not important.
  2. boolean add(int) – adds an element to the end of the list if there’s space. If there is, add it and return true. If not, return false.
  3. int get(int) – returns the value at the specified position.
  4. int size() – return the current size of the list (not necessarily the length of the array, which is the maximum capacity of the list).
  5. boolean overwriteWith(int, int) – replace the element at the specified position with the new element. If this is successful, return true. If this is impossible, return false.
  6. void overwriteWith(MyArrayList) – replace all the values in this list with the values from the other list. Note that this cannot fail, as the other list has the same capacity, so there is no return type.

Question 9 Starter Code

public class MyArrayList {

    //The array to store the data.

    public final int[] data;

    //Constructor

    public MyArrayList() {

        this.data = null;

    }

    //Add element value to the end of the list

    //return true if the element is added,

    //false if there’s no space left

    public boolean add(int value) {

        return false;

    }

    //Return the element at position

    //You don’t have to worry about

    //positions less than 0 or greater

    //than the array length – 1, but you

    //do have to worry about positions that are

    //after the end of the list. In that case

    //return 0.

    public int get(int position) {

        return Integer.MIN_VALUE;

    }

    //Return the current size of the list

    //Note that this may be different to

    //the length of the array.

    public int size() {

        return -1;

    }

    //Replace the element at position with value

    //Return true if the replacement happened,

    //false otherwise.

    public boolean overwriteWith(int position, int value) {

        return false;

    }

    //Replace the data in the list with

    //the elements of other. If other

    //is smaller than the current list,

    //the current list will get smaller.

    public void overwriteWith(MyArrayList other) {

    }

}

Order Now

Get expert help for Data Structure Algorithms and many more. 24X7 help, plag free solution. Order online now!

Universal Assignment (July 1, 2025) Data Structure and Algorithms Assignment. Retrieved from https://universalassignment.com/data-structure-and-algorithms-assignment/.
"Data Structure and Algorithms Assignment." Universal Assignment - July 1, 2025, https://universalassignment.com/data-structure-and-algorithms-assignment/
Universal Assignment July 26, 2022 Data Structure and Algorithms Assignment., viewed July 1, 2025,<https://universalassignment.com/data-structure-and-algorithms-assignment/>
Universal Assignment - Data Structure and Algorithms Assignment. [Internet]. [Accessed July 1, 2025]. Available from: https://universalassignment.com/data-structure-and-algorithms-assignment/
"Data Structure and Algorithms Assignment." Universal Assignment - Accessed July 1, 2025. https://universalassignment.com/data-structure-and-algorithms-assignment/
"Data Structure and Algorithms Assignment." Universal Assignment [Online]. Available: https://universalassignment.com/data-structure-and-algorithms-assignment/. [Accessed: July 1, 2025]

Please note along with our service, we will provide you with the following deliverables:

Please do not hesitate to put forward any queries regarding the service provision.

We look forward to having you on board with us.

Most Frequent Questions & Answers

Universal Assignment Services is the best place to get help in your all kind of assignment help. We have 172+ experts available, who can help you to get HD+ grades. We also provide Free Plag report, Free Revisions,Best Price in the industry guaranteed.

We provide all kinds of assignmednt help, Report writing, Essay Writing, Dissertations, Thesis writing, Research Proposal, Research Report, Home work help, Question Answers help, Case studies, mathematical and Statistical tasks, Website development, Android application, Resume/CV writing, SOP(Statement of Purpose) Writing, Blog/Article, Poster making and so on.

We are available round the clock, 24X7, 365 days. You can appach us to our Whatsapp number +1 (613)778 8542 or email to info@universalassignment.com . We provide Free revision policy, if you need and revisions to be done on the task, we will do the same for you as soon as possible.

We provide services mainly to all major institutes and Universities in Australia, Canada, China, Malaysia, India, South Africa, New Zealand, Singapore, the United Arab Emirates, the United Kingdom, and the United States.

We provide lucrative discounts from 28% to 70% as per the wordcount, Technicality, Deadline and the number of your previous assignments done with us.

After your assignment request our team will check and update you the best suitable service for you alongwith the charges for the task. After confirmation and payment team will start the work and provide the task as per the deadline.

Yes, we will provide Plagirism free task and a free turnitin report along with the task without any extra cost.

No, if the main requirement is same, you don’t have to pay any additional amount. But it there is a additional requirement, then you have to pay the balance amount in order to get the revised solution.

The Fees are as minimum as $10 per page(1 page=250 words) and in case of a big task, we provide huge discounts.

We accept all the major Credit and Debit Cards for the payment. We do accept Paypal also.

Popular Assignments

Nursing Ethics and Law – Henry Pearson Case Study

Nursing Ethics and Law – Henry Pearson Case Study Course Code & NameNUR1103 |Context of Professional PracticeAssessment Item and NameAssessment THREE | Case StudyAssessment Item TypeEssay/ Case studyDue Date & TimeWeek 10 | 15th March 23:59 hrsLengthEssay is 1200 words + or – 10%Marks and WeightingOverall mark is out of

Read More »

NUR3397 – Complex Care Case Study Presentation

Course Code & NameNUR3397 |Complex Care AAssessment Item and NameAssessment TWO | PresentationAssessment Item TypeIndividual oral presentationDue Date & TimeWeek 10 | 22nd April 23:59 hrsResults data will be returned to you three weeks after your submission dateLength12-15 minute oral presentation recorded to ZOOM cloud + or – 10%Marks and

Read More »

AI in Recruitment: Legal and Ethical Implications for Harmony Haven

PurposeThis assessment helps you demonstrate report-writing skills essential for HR and other professional roles. It develops your research abilities, including sourcing, reviewing, and synthesizing academic and non-academic literature. Strong report-writing skills support informed business decisions, enhancing your ability to assist managers and advance your career. AI in Recruitment: Legal and

Read More »

Youth Justice Crisis: Indigenous Incarceration in Australia

issues During Impact Root  cause Youth justice crisis ongoing Disproportionate indigenous youth incarcerations reports of abuse eg Don Dale Low age of criminal responsibility (10) – Systemic racism and overpolicing – Lack of diversion and rehabilitation pathways Word: 1000 Topic selected: Youth Justic Crisis, Assessment 1: Conflict Analysis Exercise –

Read More »

PV System Design and Energy Analysis for Residential Use

Executive Summary Provide a brief summary of the key methods and key results, max 500 words. 1.         Introduction (aims and objectives and brief description of the system studied and methods of the next sections) approximately half a page 2.         Solar irradiation analysis Provide location and data used. Provide hourly GHI,

Read More »

Assignment 3: Statistical Analysis and Recommendations for Enhancing HDI

Student Name:               Your full name Student ID:                     Your Student ID Make sure to delete the instructions!! Introduction: Include a succinct introduction at the start of your report. You may write a few sentences about purpose of this report, the type of analysis, or any other relevant information (about 50 words).

Read More »

Brian Old Age Case study Assignment

Assessment 1 – Written AssessmentAssessment TypePurposeDescriptionWritten AssignmentThe purpose of this assessment is to broaden each student’s understanding of the modulecontent using a case study and assessment toolsCase Study: Brian is an 84-year-old retired farmer in a rural area in Northern Territory. Hewas recently assessed following a minor motor vehicle accident

Read More »

Assessment name: Portfolio of planning cycle

Assessment name: Portfolio of planning cycleDue Date: Friday 13 June 11:59pmWeighting: 50%Length: 2000 wordsTask Description: This Portfolio is comprised of two tasks. You must submit your assessment as onedocument. Task 1: Anecdotal record and learning experienceAnecdotal recordView the video of pre-schoolers provided under the link “Video for Assessment 2” andcomplete

Read More »

NUR5327 Assessment 3 Assignment Help

Name NUR5327 Assessment 3 (Essay)Purpose The purpose of this assessment is to demonstrate your understanding of therolesof leadership and management in healthcare by identifying and analysinga change you have actively participated in, and how it relates to key topicssuch as interprofessional communication, evidence-based practice, and staffdevelopment.LearningOutcomes NUR5327 Assessment 3 Assignment

Read More »

Mathematics Investigation and Reflection Assignment Help

Submission: Mathematics Investigation and Reflection Assignment Help TurnitinFormat:Individual written document.Uses the current APA referencing style correctly.Length:2,000 wordsThreshold Detail:For this assessment task you must obtain at least 50% of the overall result (i.e. 25 points). If the total result for this unit is at least 50 points but you scored less

Read More »

FASS Research Proposal Template Assignment

FASS Research Proposal Template Word length2000 to 3000 wordsTitleUse a concise and descriptive title that accurately reflects the content of the proposal.Background context and significanceThis section should explain the background and context of the proposed research work,indicating the main contribution to knowledge you wish to make.Aims and objectivesInclude a clear

Read More »

Evidence to Inform Nursing Practice Assignment Help

Unit Code:   NURS12165 Unit Title:    Evidence to Inform Nursing Practice Assessment Three Type:                               Written Assessment Due date:                         Week 11: Wednesday, 28 May 2025 at 1600 (AEST) Extensions:                     Available as per policy Return date:                    Results for this assessment will be made available on Wednesday, 18 June 2025 Weighting:                       50% Length:                           

Read More »

NUR1120 | Burden of Disease and Health Equity

Assessment Item Task SheetCourse code andnameNUR1120 | Burden of Disease and Health Equity Assessment itemand nameAssessment Three | ReportDue date and time Week 11 | 22/04/2025 at 2359 hours AESTLength 1400 words (+/- 10% in each section) – includes in-text references, but not reference list.Marks out of:Weighting:80 Marks50%Assessed CourseLearning Outcomes(CLO)CLO1,

Read More »

PSY1040 Portfolio: Cultural Responsiveness & Self-Awareness

Course Code and NamePSY1040: An Introduction to Cultural Safety in PracticeAssessment Item Number and NameAssessment 2: PortfolioAssessment Item TypePortfolio PSY1040 Portfolio: Cultural Responsiveness & Self-AwarenessDue Date & TimeTuesday, 29 April 2025 (Week 12), 11:59pmLength2000 words – an average of 400 words per task.Marks and WeightingMarked out of: 100Weighting: 50%Assessed Course

Read More »

Innovative Digital App Development Report

OVERALL DESCRIPTION OF TYPE OF ASSIGNMENT Assessment 1- Type of Assignment Individual Written Report Details Individual Written Report 3,000 words (500 words of the Report is Contextualisation) Weighting of Assessment : 70% INDIVIDUAL MARK Learning outcomes assessed by Assessment: 1, 2, 3 and 4 – See Module Listings of Learning

Read More »

Tourism Trends and Investment Decisions: A Comparative Study

Assignment TaskYou are a strategist working for a major hospitality group based in Australia. The company is planninginternational expansion, and the board has asked you to compile a report to identify the most suitablelocation for the project. The board has shortlisted two international locations (which will be allocatedto you by

Read More »

EC502 Language and Literacy in the Early Years

EC502 Language and Literacy in the Early Years Unit Code/Description EC502 Language and Literacy in the Early Years Course/Subject Bachelor of Early Childhood Education Semester March 2025 Assessment Overview   Unit Learning Outcomes Addressed 1, 2, 3 Assessment Objective Assessment 1: Poster Including an Invigilated stage in Week 3. Due

Read More »

EC501 Early Childhood Learning and Development

Unit Code/Description EC501 Early Childhood Learning and Development Course/Subject Graduate Diploma in Education (early childhood) Semester S 1, 2025 Assessment Overview   Unit Learning Outcomes Addressed 1, 2, 3 Assessment Objective In this assessment, student are required to select one of the case studies provided and critically analyze the child’s

Read More »

JSB172: Professional Academic Skills

JSB172: Professional Academic SkillsAssessment: Workplace Report and Presentation Weight: 50%Due date: Friday 30th May 11:59pm Length: 1,750 words (+/- 10 %) / 5minutesPurpose/Learning Objectives:This assessment relates to Learning Outcomes 1, 2, 3, and 4: Task:Your task is to write a Workplace Report identifying how to address the topic/issue chosen or

Read More »

2015PSY Developmental Psychology Assignment

2015PSY Developmental Psychology Assignment 2025 2015PSY Developmental Psychology Assignment Assignment MaterialsAssignment Information Sheet & Marking Criteria.pdf (this document)Assignment Template.docx (template)Example Assignment.pdf (HD exemplar)Due Date: Friday 16 May, 11:59PM (Week 10)Weighting: Marked out of 100 (worth 30% of course grade)Word Count: 1,500 words maximum(inclusive of main text, headings, in-text citations; excluding

Read More »

Principles of Economics Federal Budget

Principles of Economics Short-answer Assignment V1 (20% of final mark) The assignment consists of four questions.  You should allocate at least half a page (or 250 words) to each answer or 1000 words for all four answers depending on the nature of and/or marks allocated for the question/s. You may

Read More »

LML6003 – AUSTRALIA’S VISA SYSTEM 1 (FAMILY AND OTHERVISAS)

Graduate Diploma in Migration Law LML6003 – AUSTRALIA’S VISA SYSTEM 1 (FAMILY AND OTHER VISAS) Assessment Task 2 – Semester 1, 2025 LML6003 – AUSTRALIA’S VISA SYSTEM 1 (FAMILY AND OTHERVISAS) Instructions: 1. Students must answer all questions as indicated. Make certain all answers are clearly labelled. 2. Make certain

Read More »

Construction Cadetships in the Australian Construction Industry

REPORT TOPICPrepare an Academic Report on the following:‘Construction Cadetships in the Australian Construction Industry’.The report should encompass the following: Your personal evaluation and critique of the key findings in your report including your evaluation of construction cadetships, yourfindings in relation to potential issues/problems with cadetships and your recommendations to improve

Read More »

Assessing Corporate Governance and its Significance

Assessing Corporate Governance and its Significance: A Case Study Analysis Overview: Accounting irregularities have cost investors millions of dollars and, most importantly, adversely impacted their confidence in the financial system. While there have been remarkable improvements in regulatory supervision, auditing framework and reporting transparency, young graduates must assess major corporate

Read More »

Master of Professional Accounting and Accounting Advanced

Assessment 2 – Business Case (CVP) AnalysisUnit Code/Description ACC901 Accounting for Managerial DecisionsCourse/Subject Master of Professional Accounting and Master of Professional Accounting AdvancedSemester S1 2025 Assessment Overview Unit Learning OutcomesAddressed1,2,3,4 and 5Assessment Objective The primary objective of this assessment is to assess the students’ ability to apply CVPanalysis and relevant

Read More »

Urban Design Theory Essay writing

Essays are a major form of assessment at university. Through essays, you develop your understanding of discipline-specific content, strengthen your critical thinking, and develop your ability to translate that thinking into a persuasive written form. This assignment assesses your understanding of the following Unit Learning Outcomes: 1) understand the historic

Read More »

Statutory Interpretation of Disability Discrimination in NSW Law

Foundations of Law 70102 – Assessment Task 3 – Autumn 2025Statutory Interpretation and Research ExerciseDue: Thursday 22 May 2025 by 23.59Length: 2000 words (excluding the headings Part A, Part B and Part C, footnotes andbibliography. Any additional headings that you decide to use will be included in the wordcount)Weighting: 40%Task

Read More »

Can't Find Your Assignment?