Question: Please implement the following in the code. Also, provide a screenshot of the test. This is a string calculator implemented using Java 2. Delimiters can
Please implement the following in the code. Also, provide a screenshot of the test. This is a string calculator implemented using Java
2. Delimiters can be arbitrary length a. //*** 1***2***3 - Result 6 3. Allow for multiple delimiters a. //$,@ 1$2@3 - Result 6 4. Combine 2 and 3 bonus questions. Allow multiple delimiters of arbitrary length
Here's the code:
import static org.junit.Assert.assertEquals; class Calculate { static int Add(String numbers) { String delimiter = ","; numbers = numbers.trim(); if(numbers.isEmpty()) { return 0; } // Check for delimiter if(numbers.startsWith("//")) { numbers = numbers.substring(2); int x = numbers.indexOf(" "); delimiter = numbers.substring(0, x); numbers = numbers.substring(x+1); } int sum = 0; // Handle new line numbers = numbers.replace(" ", ""); if(numbers.isEmpty()) { return 0; } /// create scanner to read numbers boolean done = false; while(!done) { int index = numbers.indexOf(delimiter); int x; if(index != -1) { x = Integer.parseInt(numbers.substring(0, index)); numbers = numbers.substring(index+1); } else { x = Integer.parseInt(numbers); done = true; } if(x < 0) { throw new IllegalArgumentException("Negatives not allowed: " + x); } if(x <= 1000) { sum += x; } } return sum; } } public class TestCalculate { public static void main(String[] args) { assertEquals(0, Calculate.Add("")); assertEquals(0, Calculate.Add(" ")); assertEquals(0, Calculate.Add(" ")); assertEquals(8, Calculate.Add("8")); assertEquals(8, Calculate.Add("1,2,5")); assertEquals(6, Calculate.Add("1 ,2,3")); assertEquals(6, Calculate.Add("//; 1;2;3")); assertEquals(8, Calculate.Add("//; 1;3;4")); assertEquals(6, Calculate.Add("//$ 1$2$3")); assertEquals(13, Calculate.Add("//@ 2@3@8")); assertEquals(2, Calculate.Add("2,1001")); System.out.println("All tests passed successfully!"); } } Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
