Question

In: Computer Science

public class OperationsBetween { // You must define the following: // 1.) Two private instance variables,...

public class OperationsBetween {
    // You must define the following:
    // 1.) Two private instance variables, min and max
    //
    // 2.) A constructor which takes initial values for
    //     min and max
    //
    // 3.) An instance method named sum, which sums the
    //     values between min and max and returns the
    //     result.  For example, if min = 3 and max = 5,
    //     then this should return 12 (3 + 4 + 5).  If
    //     min is greater than max, then this should
    //     return 0.
    //
    // 4.) An instance method named product, which
    //     multiplies the values between min and max and
    //     returns the result.  For example, if min = 6
    //     and max = 9, then this should return 3024
    //     (6 * 7 * 8 * 9).  If min is greater than
    //     max, then this should return 1.  A stub has
    //     been provided that simply returns 1; this is
    //     just to allow things to compile while you're
    //     working on the sum method.

    public int product() {
        // You'll need to replace this code with something
        // else to make product() work; this is just to make
        // things compile while you work on sum()
        return 1;
    }

    // DO NOT MODIFY main!
    public static void main(String[] args) {
        OperationsBetween between =
            new OperationsBetween(Integer.parseInt(args[0]),
                                  Integer.parseInt(args[1]));
        System.out.println("Sum: " + between.sum());
        System.out.println("Product: " + between.product());
    }
}

Step 1: Get OperationsBetween.java Compiling

Download the OperationsBetween.java file, and open it in jGrasp (or a text editor of your choice). This program takes two command-line arguments representing the minimum and maximum number in a numeric range. Currently, the code does not compile. As a first step, you need to get this code to compile. To this end, you'll need to implement the following:

  • Instance variables
  • Constructor
  • A “stub” for the sum method, which will allow the call to sum in the main method to compile. A stub has already been written for the product method; you should write something similar for sum.

Once the code has the above elements and is compiling, you're ready to move on to the next step.

Step 2: Implement the sum Method

In the previous step, you wrote a stub for sum to get the code compiling. Now replace the code in the stub with a loop that will compute the sum between min and max. You will need to use a loop for this purpose, and a for loop is likely the best fit. You should start from min, and then iterate up to max, using a temporary variable that you increment along the way. You will also need another variable to store the result. Comments in the file contain further details.

Once sum (and only sum) is correctly implemented, you should see the following output if run with the command-line arguments 3 4:

Sum: 7
Product: 1

Step 3: Implement the product Method

Replace the code in the stub for product with a loop that will compute the product between min and max. This code should look very similar to the code you wrote for sum. Further details are in the file.

Once both product and sum are correctly implemented, you should see the following output if run with the command-line arguments 5 8:

Sum: 26
Product: 1680

Further example output is shown below for the command-line arguments 3 2 (note that the minimum end of the range is greater than the maximum end of the range):

Sum: 0
Product: 1

Further example output is shown below for the command-line arguments 3 3 (the minimum end of the range is equal to the maximum end of the range):

Sum: 3
Product: 3
import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class OperationsBetweenTest {
    public static OperationsBetween makeOp(int min, int max) {
        return new OperationsBetween(min, max);
    }
    
    @Test
    public void testSumOutOfRange() {
        assertEquals(0, makeOp(0, -1).sum());
    }

    @Test
    public void testSumRange1() {
        assertEquals(2, makeOp(2, 2).sum());
    }

    @Test
    public void testSumRange2() {
        assertEquals(5, makeOp(2, 3).sum());
    }

    @Test
    public void testSumRange3() {
        assertEquals(9, makeOp(2, 4).sum());
    }

    @Test
    public void testProductOutOfRange() {
        assertEquals(1, makeOp(0, -1).product());
    }

    @Test
    public void testProductRange1() {
        assertEquals(3, makeOp(3, 3).product());
    }

    @Test
    public void testProductRange2() {
        assertEquals(6, makeOp(2, 3).product());
    }

    @Test
    public void testProductRange3() {
        assertEquals(24, makeOp(2, 4).product());
    }
}

Solutions

Expert Solution

public class OperationsBetween {
    // You must define the following:
    // 1.) Two private instance variables, min and max
    private int min, max;
    //
    // 2.) A constructor which takes initial values for
    //     min and max

    public OperationsBetween(int min, int max) {
        this.min = min;
        this.max = max;
    }

    //
    // 3.) An instance method named sum, which sums the
    //     values between min and max and returns the
    //     result.  For example, if min = 3 and max = 5,
    //     then this should return 12 (3 + 4 + 5).  If
    //     min is greater than max, then this should
    //     return 0.
    //
    public int sum() {
        int total = 0;
        for (int i = min; i <= max; i++) {
            total += i;
        }
        return total;
    }
    // 4.) An instance method named product, which
    //     multiplies the values between min and max and
    //     returns the result.  For example, if min = 6
    //     and max = 9, then this should return 3024
    //     (6 * 7 * 8 * 9).  If min is greater than
    //     max, then this should return 1.  A stub has
    //     been provided that simply returns 1; this is
    //     just to allow things to compile while you're
    //     working on the sum method.

    public int product() {
        int result = 1;
        for (int i = min; i <= max; i++) {
            result *= i;
        }
        return result;
    }

    // DO NOT MODIFY main!
    public static void main(String[] args) {
        OperationsBetween between =
                new OperationsBetween(Integer.parseInt(args[0]),
                        Integer.parseInt(args[1]));
        System.out.println("Sum: " + between.sum());
        System.out.println("Product: " + between.product());
    }
}



Related Solutions

public class OperationsBetween { // You must define the following: // 1.) Two private instance variables,...
public class OperationsBetween { // You must define the following: // 1.) Two private instance variables, min and max   // 2.) A constructor which takes initial values for // min and max // 3.) An instance method named sum, which sums the // values between min and max and returns the // result. For example, if min = 3 and max = 5, // then this should return 12 (3 + 4 + 5). If // min is greater than...
Complete the required methods: public class SongList { // instance variables private Song m_last; private int...
Complete the required methods: public class SongList { // instance variables private Song m_last; private int m_numElements; // constructor // Do not make any changes to this method! public SongList() { m_last = null; m_numElements = 0; } // check whether the list is empty // Do not make any changes to this method! boolean isEmpty() { if (m_last == null) return true; else return false; } // return the size of the list (# of Song nodes) // Do...
Write a class called Pen that contains the following information: Private instance variables for the price...
Write a class called Pen that contains the following information: Private instance variables for the price of the pen (float) and color of the pen (String). A two-argument constructor to set each of the instance variables above. If the price is negative, throw an IllegalArgumentException stating the argument that is not correct. Get and Set methods for each instance variable with the same error detection as the constructor. public class Pen {
1. Define a class counterType to implement a counter. Your class must have a private data...
1. Define a class counterType to implement a counter. Your class must have a private data member counter of type int and functions to set counter to the value specified by the user, initialize counter to 0, retrieve the value of counter, and increment and decrement counter by one. The value of counter must be nonnegative. 2. Some of the characteristics of a book are the title, author(s), publisher, ISBN, price, and year of publication. Design a class bookType that...
public class AddValueToArray { // You must define the addValueTo method, which will add // a...
public class AddValueToArray { // You must define the addValueTo method, which will add // a given value to each element of the given array. // // TODO - define your code below this comment // // DO NOT MODIFY main! public static void main(String[] args) { int[] array = new int[]{3, 8, 6, 4}; int valueToAdd = Integer.parseInt(args[0]); addValueTo(valueToAdd, array); for (int index = 0; index < array.length; index++) { System.out.println(array[index]); } } }
myLinkedList.java>>>>>>>> public class MyLinkedList implements MiniList<Integer>{ /* Private member variables that you need to declare: **...
myLinkedList.java>>>>>>>> public class MyLinkedList implements MiniList<Integer>{ /* Private member variables that you need to declare: ** The head pointer ** The tail pointer */ public class Node { // declare member variables (data and next) // finish these constructors public Node(int data, Node next) {} public Node(int data) {} // HINT: use this() with next = null } // Initialize the linked list (set head and tail pointers) public MyLinkedList() {} @Override public boolean add(Integer item) { return false; }...
(java) Write a class called CoinFlip. The class should have two instance variables: an int named...
(java) Write a class called CoinFlip. The class should have two instance variables: an int named coin and an object of the class Random called r. Coin will have a value of 0 or 1 (corresponding to heads or tails respectively). The constructor should take a single parameter, an int that indicates whether the coin is currently heads (0) or tails (1). There is no need to error check the input. The constructor should initialize the coin instance variable to...
public class AllEqual { // You must define the allEqual method, which will return // true...
public class AllEqual { // You must define the allEqual method, which will return // true if either: // 1.) The given array contains fewer than two elements, or... // 2.) All elements of the array are equal to each other. // As a hint, you only need to compare the first element // to all subsequent elements for this check. // // TODO - define your code below this comment // // DO NOT MODIFY parseStrings! public static int[]...
public class AddValueNewArray { // You must define the addValueNew method, which behaves // similarly to...
public class AddValueNewArray { // You must define the addValueNew method, which behaves // similarly to the addValueTo method in AddValueToArray.java. // However, instead of adding the given value to the given // array, it will return a _new_ array, where the new array // is the result of adding the value to each element of the // given array. To be clear, the given array NEVER CHANGES. // // TODO - define your code below this comment // //...
public class StringNode { private String item; private StringNode next; } public class StringLL { private...
public class StringNode { private String item; private StringNode next; } public class StringLL { private StringNode head; private int size; public StringLL(){ head = null; size = 0; } public void add(String s){ add(size,s); } public boolean add(int index, String s){ ... } public String remove(int index){ ... } } In the above code add(int index, String s) creates a StringNode and adds it to the linked list at position index, and remove(int index) removes the StringNode at position...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT