Question

In: Computer Science

JAVA programming language Please add or modify base on the given code Adding functionality Add functionality...

JAVA programming language

Please add or modify base on the given code

Adding functionality

  • Add functionality for multiplication (*)

Adding JUnit tests

  • Add one appropriately-named method to test some valid values for tryParseInt
    • You will use an assertEquals
    • You'll check that tryParseInt returns the expected value
    • The values to test:
      • "-2"
      • "-1"
      • "0"
      • "1"
      • "2"
    • Hint: You will need to cast the return value from tryParseInt to an int
    • e.g., (int) ValidationHelper.tryParseInt("1")
  • Add one appropriately-named method to test some invalid values for tryParseInt
    • I'm leaving it to you to choose the correct assert to use
    • The values to test:
      • ""
      • " "
      • " "
      • "1.2.3"
      • "."
      • "x"
      • "one"
      • null that is not in quotes
  • Add one appropriately-named method to test some valid values for isCharAllowed
    • I'm leaving it to you to choose the correct assert to use
    • The values to test:
      • ('a', "abc")
      • ('b', "abc")
      • ('a', "a")
      • (' ', " ") That's a one-space char, and a one-space string
  • Add one appropriately-named method to test some invalid values for isCharAllowed
    • I'm leaving it to you to choose the correct assert to use
    • The values to test:
      • ('a', "")
      • ('b', "xyz")
      • ('a', null)
      • ('z', " ") That's a one-space string

----------------------------------------------------

Given code

Main.java

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

        int operandOne = IOHelper.userInputInt("Enter first numeric value");
        int operandTwo = IOHelper.userInputInt("Enter second numeric value");
        char operation = IOHelper.userInputChar("Choose an operation", "+-");

        double result;
        switch (operation) {
            case '+':
                result = MathHelper.addValues(operandOne, operandTwo);
                break;
            case '-':
                result = MathHelper.subtractValues(operandOne, operandTwo);
                break;
            default:
                System.out.println("Unrecognized operation!");
                return;
        }
        System.out.println("The answer is " + result);
    }
}

-------------------------------------

IOHelper.java


import java.util.Scanner;

public class IOHelper {
    private static final Scanner keyboard = new Scanner(System.in);

    public static String userInputString(String x) {
        System.out.print(x + ": ");

        return keyboard.nextLine();
    }

    public static int userInputInt(String x) {
        Integer o = null;

        while (o == null) {
            String u = userInputString(x);
            o = ValidationHelper.tryParseInt(u);
        }

        return o;
    }

    public static char userInputChar(String x, String r) {

        char c = 0;
        while (!ValidationHelper.isCharAllowed(c, r)) {
            String i = userInputString(x + " (" + r + ")");
            if (i.length() > 0) {
                c = i.charAt(0);
            }
        }

        return c;
    }
}


-----------------------

MathHelper.java

public class MathHelper {
    public static double addValues(double operandOne, double operandTwo) {
        return operandOne + operandTwo;
    }

    public static double subtractValues(double operandOne, double operandTwo) {
        return operandOne - operandTwo;
    }

}


------------------------

ValidationHelper.java

public class ValidationHelper {

    public static Integer tryParseInt(String userInput) {
        try {
            return Integer.parseInt(userInput);
        } catch (Exception e) {
            return null;
        }
    }

    public static boolean isCharAllowed(char ch, String r) {
        if (r == null) {
            return false;
        }
        return (r.indexOf(ch) >= 0);
    }
}

Solutions

Expert Solution

NOTE: The ValidationHelper.java and IOHelper.java remains the same as given in the question. Please find MathHelper.java, Main.java and JunitTests.java below.

// MathHelper.java
public class MathHelper {
   /**
   * This method adds the two given double values and returns the result.
   *
   * @param operandOne
   * - value 1
   * @param operandTwo
   * - value 2
   */
   public static double addValues(double operandOne, double operandTwo) {
       return operandOne + operandTwo;
   }

   /**
   * This method subtracts the second double value from the first double value
   * and returns the result.
   *
   * @param operandOne
   * - value 1
   * @param operandTwo
   * - value 2
   */
   public static double subtractValues(double operandOne, double operandTwo) {
       return operandOne - operandTwo;
   }

   /**
   * This method multiplies the two given double values and returns the
   * result.
   *
   * @param operandOne
   * - value 1
   * @param operandTwo
   * - value 2
   */
   public static double multiplyValues(double operandOne, double operandTwo) {
       return operandOne * operandTwo;
   }
}

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

       int operandOne = IOHelper.userInputInt("Enter first numeric value");
       int operandTwo = IOHelper.userInputInt("Enter second numeric value");
       char operation = IOHelper.userInputChar("Choose an operation", "+-*");

       double result;
       switch (operation) {
       case '+': // Addition
           result = MathHelper.addValues(operandOne, operandTwo);
           break;
       case '-': // Subtraction
           result = MathHelper.subtractValues(operandOne, operandTwo);
           break;
       case '*': // Multiplication
           result = MathHelper.multiplyValues(operandOne, operandTwo);
           break;
       default:
           System.out.println("Unrecognized operation!");
           return;
       }
       System.out.println("The answer is " + result);
   }
}

// JunitTests.java
import org.junit.Test;
import static org.junit.Assert.*;

public class JunitTests {

   /**
   * This method tests valid integers by passing them to the
   * ValidationHelper.tryParseInt() method.
   */
   @Test
   public void testValidInts() {
       assertEquals(-2, (int) ValidationHelper.tryParseInt("-2"));
       assertEquals(-1, (int) ValidationHelper.tryParseInt("-1"));
       assertEquals(0, (int) ValidationHelper.tryParseInt("0"));
       assertEquals(1, (int) ValidationHelper.tryParseInt("1"));
       assertEquals(2, (int) ValidationHelper.tryParseInt("2"));
   }

   /**
   * This method tests invalid integers by passing them to the
   * ValidationHelper.tryParseInt() method.
   */
   @Test
   public void testInvalidInts() {
       assertNull(ValidationHelper.tryParseInt(""));
       assertNull(ValidationHelper.tryParseInt(" "));
       assertNull(ValidationHelper.tryParseInt("1.2.3"));
       assertNull(ValidationHelper.tryParseInt("."));
       assertNull(ValidationHelper.tryParseInt("x"));
       assertNull(ValidationHelper.tryParseInt("one"));
       assertNull(ValidationHelper.tryParseInt(null));
   }

   /**
   * This method tests valid integers by passing them to the
   * ValidationHelper.isCharAllowed() method.
   */
   @Test
   public void testValidChar() {
       assertTrue(ValidationHelper.isCharAllowed('a', "abc"));
       assertTrue(ValidationHelper.isCharAllowed('b', "abc"));
       assertTrue(ValidationHelper.isCharAllowed('a', "a"));
       assertTrue(ValidationHelper.isCharAllowed(' ', " "));
   }

   /**
   * This method tests invalid integers by passing them to the
   * ValidationHelper.isCharAllowed() method.
   */
   @Test
   public void testInvalidChar() {
       assertFalse(ValidationHelper.isCharAllowed('a', ""));
       assertFalse(ValidationHelper.isCharAllowed('b', "xyz"));
       assertFalse(ValidationHelper.isCharAllowed('a', null));
       assertFalse(ValidationHelper.isCharAllowed('z', " "));
   }
}

CODE SCREENSHOTS

SAMPLE OUTPUT

OUTPUT of Main.java

JunitTest.java output


Related Solutions

Given the following code for AES Electronic Code Block implementation for the encryption functionality. Modify the...
Given the following code for AES Electronic Code Block implementation for the encryption functionality. Modify the code to create a function named ‘encryptECB(key, secret_message)’ that accepts key and secret_message and returns a ciphertext.          #Electronic Code Block AES algorithm, Encryption Implementation from base64 import b64encode from Crypto.Cipher import AES from Crypto.Util.Padding import pad from Crypto.Random import get_random_bytes secret_message = b" Please send me the fake passport..." password = input ("Enter password to encrypt your message: ") key= pad(password.encode(), 16) cipher...
4. Given the following code for AES Electronic Code Block implementation for the encryption functionality. Modify...
4. Given the following code for AES Electronic Code Block implementation for the encryption functionality. Modify the code to create a function named ‘decryptECB(key, ciphertext)’ that accepts key and ciphertext and returns a plaintext. from base64 import b64decode from Crypto.Cipher import AES from Crypto.Util.Padding import pad from Crypto.Util.Padding import unpad # We assume that the password was securely shared beforehand password = input ("Enter the password to decrypt the message: ") key= pad(password.encode(), 16) ciphertext = input ("Paste the cipher...
Modify Account Class(Java programming) used in the exercises such that ‘add’ and ‘deduct’ method could only...
Modify Account Class(Java programming) used in the exercises such that ‘add’ and ‘deduct’ method could only run if the account status is active. You can do this adding a Boolean data member ‘active’ which describes account status (active or inactive). A private method isActive should also be added to check ‘active’ data member. This data member is set to be true in the constructor, i.e. the account is active the first time class Account is created. Add another private method...
Language for this question is Java write the code for the given assignment Given an n...
Language for this question is Java write the code for the given assignment Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of matrix in sorted order.Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer n denoting the size of the matrix. Then the next line contains the n x n elements...
C Programming Please modify this code to display the "guess" value from the calculation and the...
C Programming Please modify this code to display the "guess" value from the calculation and the "iterations" it took to complete. Please also add the input to the program. Input: Program will prompt the user to provide the desired decimal-place accuracy, in the range of [1-15], inclusive. User prompt must clearly indicate what is a valid input. User input must be validated - ensuring that the value entered is an integer in the above range. Sample output for one perfect...
Java: modify the given example code to make it possible to create a student object by...
Java: modify the given example code to make it possible to create a student object by only specifying the name, all other info may be absent. it may also be possible to add a tag with an absent value. use OPTIONAL TYPE and NULL object design pattern.   import java.util.HashMap; import java.util.Map; public class Student { private final String aName; private String aGender; private int aAge; private Country aCountry; private Map aTags = new HashMap<>(); public Student(String pName) { aName =...
Java: modify the given example code to make it possible to create a student object by...
Java: modify the given example code to make it possible to create a student object by only specifying the name, all other info may be absent. it may also be possible to add a tag with an absent value. import java.util.HashMap; import java.util.Map; public class Student { private final String aName; private String aGender; private int aAge; private Country aCountry; private Map<String, String> aTags = new HashMap<>(); public Song(String pName) { aName = pName; } public String getName() { return...
The programming language that is being used here is JAVA, below I have my code that...
The programming language that is being used here is JAVA, below I have my code that is supposed to fulfill the TO-DO's of each segment. This code in particular has not passed 3 specific tests. Below the code, the tests that failed will be written in bold with what was expected and what was outputted. Please correct the mistakes that I seem to be making if you can. Thank you kindly. OverView: For this project, you will develop a game...
Code in Java Given the LinkedList class that is shown below Add the following methods: add(String...
Code in Java Given the LinkedList class that is shown below Add the following methods: add(String new_word): Adds a linkedlist item at the end of the linkedlist print(): Prints all the words inside of the linkedlist length(): Returns an int with the length of items in the linkedlist remove(int index): removes item at specified index itemAt(int index): returns LinkedList item at the index in the linkedlist public class MyLinkedList { private String name; private MyLinkedList next; public MyLinkedList(String n) {...
2. Specification - Given the following code base, add the appropriate function that will give the...
2. Specification - Given the following code base, add the appropriate function that will give the correct results/output. CODE: # TODO : Add Two Missing Functions HERE mlist = [(" Orange ", 10 , 0.25) ,( " Apple ", 5 , .20) , (" Banana ", 2 , 0.3) ,(" Kiwi ", 1 , 0.5)] addFruit (10 ," Lemon " ,0.1) displayFruitList ( mlist ) OUTPUT: Orange --- $ 2.50 Apple --- $ 1.00 Banana --- $ 0.60 Kiwi ---...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT