testing program with switch case using junit - java

I want to write test case for calculator program in junit. I am new to junit environment. I can write tests for other programs but kind of stuck with testing for switch() case.
I really want to know how to to do it.
thanks in advance
here is my program
import java.util.Scanner;
//This program performs basic math operations such as :- +,-,*,/
public class Calculator
{
public static void main(String[] args)
{
double number1, number2;
String Mathoperation;
Scanner scannerObject = new Scanner(System.in);
System.out.println("Enter first number");
number1 = scannerObject. nextDouble();
System.out.println("Enter second number");
number2 = scannerObject. nextDouble();
Scanner UserInput = new Scanner(System.in);
System.out.println("\nHere are your options:");
System.out.println("\n1. Addition, 2. Subtraction, 3. Divison, 4. Multiplication");
Mathoperation = UserInput.next();
switch (Mathoperation)
{
case "1":
System.out.println("Your answer is " + (number1 + number2));
break;
case "2":
System.out.println("Your answer is " + (number1 - number2));
break;
case "3":
System.out.println("Your answer is " + (number1 / number2));
break;
case "4":
System.out.println("Your asnwer is " + (number1 * number2));
break;
default:
System.out.println("");
}
}
}

The first step to writing unit tests is writing testable code. At this point your code isn't very testable, which is to say you can test it but it won't be the best tests. Lets have a look at why.
The first reason is that you have all your code in your main function. You usually want to avoid this. There are multiple reasons for this, but the two biggest in my opinion are readability and reusability. Normally you would want to put things into different classes, but for the sake of time we will simply put your math switch into its own function.
import java.util.Scanner;
//This program performs basic math operations such as :- +,-,*,/
public class Calculator
{
public static void main(String[] args)
{
double number1, number2;
String Mathoperation;
Scanner scannerObject = new Scanner(System.in);
System.out.println("Enter first number");
number1 = scannerObject. nextDouble();
System.out.println("Enter second number");
number2 = scannerObject. nextDouble();
Scanner UserInput = new Scanner(System.in);
System.out.println("\nHere are your options:");
System.out.println("\n1. Addition, 2. Subtraction, 3. Divison, 4. Multiplication");
Mathoperation = UserInput.next();
doMath(Mathoperation, number1, number2)
}
public double doMath(String Mathoperation, double number1, double number2){
switch (Mathoperation)
{
case "1":
System.out.println("Your answer is " + (number1 + number2));
break;
case "2":
System.out.println("Your answer is " + (number1 - number2));
break;
case "3":
System.out.println("Your answer is " + (number1 / number2));
break;
case "4":
System.out.println("Your asnwer is " + (number1 * number2));
break;
default:
System.out.println("");
}
}
}
Ok cool, so now we have our own method for doing our mathematic operations. One issue tho. This isn't a unit in of itself, this is actually an integration between addition and our math operation. What this means is, to test, we would need to test each combination of arithmetic (add, sub, divide, multiply) as well as if the method selects the right operator. Thats alot more work then we want, and isn't a very good test, so how do we fix this? Well simple, we break it down further
import java.util.Scanner;
//This program performs basic math operations such as :- +,-,*,/
public class Calculator {
//Code for use input somewhere here
public double doMath(String Mathoperation, double number1, double number2){
switch (Mathoperation)
{
case "1":
System.out.println("Your answer is " + add(number1, number2));
break;
case "2":
System.out.println("Your answer is " + sub(number1, number2));
break;
case "3":
System.out.println("Your answer is " + div(number1, number2));
break;
case "4":
System.out.println("Your answer is " + mul(number1, number2));
break;
default:
System.out.println("");
}
}
public double add(double number1, double number2){
return number1 + number2;
}
public double sub(double number1, double number2){
return number1 - number2;
}
public double mul(double number1, double number2){
return number1 * number2;
}
public double div(double number1, double number2){
return number1 / number2;
}
}
Now our units are broken down much more easily. From here you would write test for your add, sub, div, and mul functions. Test these out well to insure that they function as expected. Then write tests for the doMath function to make sure it passes the values to the right operation. In this way when something fails you know exactly where its failing and what the issue is, as oppose to having to guess. You will know if doMath has an issue, or if one of your other math methods is the problem. It also allows you to more easily reuse your methods for other things, so win-win

Consider putting the input, calculation and output into (non static) methods, which will make testing of the logic possible :
//This program performs basic math operations such as :- +,-,*,/
public class Calculator {
double number1, number2;
String Mathoperation;
Calculator()
{
//you need to remove input and calculation logic from constructor,
//to avoid running it when constructing this object for testing.
}
public void run() {
getInput();
double result = doMath(Mathoperation, number1, number2 );
System.out.println("Your answer is " + result );
}
private void getInput() {
Scanner scannerObject = new Scanner(System.in);
System.out.println("Enter first number");
number1 = scannerObject. nextDouble();
System.out.println("Enter second number");
number2 = scannerObject. nextDouble();
Scanner UserInput = new Scanner(System.in);
System.out.println("\nHere are your options:");
System.out.println("\n1. Addition, 2. Subtraction, 3. Divison, 4. Multiplication");
Mathoperation = UserInput.next();
}
/**
*#param mathoperation
*/
public double doMath(String mathoperation, double number1, double number2) {
switch (mathoperation)
{
case "1":
return (number1 + number2);
case "2":
return (number1 - number2);
case "3":
return (number1 / number2);
case "4":
return (number1 * number2);
default:
throw new IllegalStateException("mathoperation is not valid");
}
}
public static void main(String[] args)
{
Calculator calc = new Calculator();
calc.run();
}
}
Here is a very simple JUnit test example:
public class CalculatorTest {
/**
* Test method for {#link Calculator#doMath(java.lang.String, double, double)}.
*/
#Test
public void testDoMath() {
Calculator calc = new Calculator();
assertTrue(calc.doMath("1", 5, 7) == 12.0);
assertTrue(calc.doMath("2", 5, 7) == -2.0);
assertTrue(calc.doMath("3", 5, 7) == (5.0/7.0));
assertTrue(calc.doMath("4", 5, 7) == (5.0*7.0));
}
}

To write unit tests, you usually have to have pieces of the API that you want to test. In your case, everything is in the main method which gathers user input, so it's hard to test. You should extract something like a double performOperation(number, number, operation) method which returns the answer. Then you can write JUnit tests with different inputs to this method.

Related

How to store value in calc and continue counting?

How to modify the code so I can continuously count? So for example 2+3=5, and than -1 =4, until i press q to exit program ?? Please some simple solution for beginners. Thank you.
import java.util.Objects;
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do {
System.out.println("Enter first number:");
double num1 = sc.nextDouble();
System.out.println("Enter second number");
double num2 = sc.nextDouble();
System.out.println("Select operator (+,-,*,/) or enter q to exit:");
char operator = sc.next().charAt(0);
switch (operator) {
case '+':
System.out.println("Result =" + Equasion.sum(num1, num2));
break;
case '-':
System.out.println(Equasion.substract(num1, num2));
break;
case'/':
if (num2 == 0) {
System.out.println("Divide by zero problem");
} else System.out.println(Equasion.divide(num1, num2));
case '*':
System.out.println(Equasion.multiply(num1, num2));
break;
case 'q':
System.exit(0);
}
System.out.println("Press any key to continue or q to quit");
} while (!Objects.equals(ExitProg.exitProg(), 'q'));
}
}
Correct me if I'm wrong but you should move the first lines outside the while loop then overwrite the values of num1 and num2 every iteration (num2 becomes num1, then the user inputs another num2)

I made a CLI calculator and I am wondering, how can I have the program accept numbers indefinetly until the user inputs a stop command?

You probably understand that I am a beginner, and I know that we aren't really liked by the community.
I made a multi purpose calculator a while back and now I want to expand it. In this question I will be focusing only on one class.
import java.util.Scanner;
public class Calculator {
public static void calcMenu(Scanner input){
Scanner oper = new Scanner(System.in);
System.out.println("Please input the First number:");
double anum = input.nextDouble();
System.out.println("Please input on of the following operations:");
System.out.println("+");
System.out.println("-");
System.out.println("*");
System.out.println("/");
String equ = oper.nextLine();
System.out.println("Please input the Second number:");
double bnum = input.nextDouble();
switch (equ){
case "+":
System.out.println(anum + bnum);
break;
case "-":
System.out.println(anum - bnum);
break;
case "*":
System.out.println(anum * bnum);
break;
case "/":
System.out.println(anum / bnum);
break;
}
}
}
In this Java class, the program can solve equations only with two numbers. I would like to make it like in a standard calculator, where you can input the numbers as much as you want. I would like to do it until the user types something like "done" and the application will return to the main menu.
This is probably a very nooby question but please help. And if you want to see the whole application: here's the link
This will help you out! :)
import java.util.InputMismatchException;
import java.util.Scanner;
public class Calculator {
private static double answer;
private static boolean done = false;
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
try {
new Calculator().calcExpression();
} catch (InputMismatchException e) {
System.out.println("An error occurred. ");
}
}
private void calcExpression() throws InputMismatchException {
System.out.println("Enter Your Expression Here:");
System.out.print("Num: ");
double firstNum = in.nextDouble();
in.nextLine();
while (!done) {
System.out.print("Operator: ");
String operand = in.nextLine();
if (operand.equals("=")) {
break;
}
System.out.print("Num: ");
double secondNum = in.nextDouble();
in.nextLine();
calculate(firstNum, operand, secondNum);
firstNum = answer;
}
System.out.printf("Answer is %.2f", answer);
}
private void calculate(double num1, String equ, double num2) {
switch (equ)
{
case "/":
answer = (num1 / num2);
break;
case "*":
answer = (num1 * num2);
break;
case "+":
answer = (num1 + num2);
break;
case "-":
answer = (num1 - num2);
break;
case "=":
done = true;
break;
}
}
}

Can I make it so I don't have to add a space to get the sum?

first time posting here and I'd like some help , I started learning java some days ago and I tried to make a very simple calculator. Here is the code :
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
while (true) {
Scanner input = new Scanner(System.in);
double input1, input2;
System.out.println("Type your calculation below");
input1 = input.nextDouble();
String operator = input.next();
input2 = input.nextDouble();
switch (operator) {
case "+":
System.out.println(input1 + input2);
break;
case "-":
System.out.println(input1 - input2);
break;
case "*":
System.out.println(input1 * input2);
break;
case "/":
System.out.println(input1 / input2);
break;
}
}
}
}
When I run this I have to type a number press space and then type the other number like this : 15 + 15. Can I somehow make it so that I don't have to press space every time? So I can type it like this : 15+15.
Also if you have any tips or if you see any mistakes I'd be happy to hear your opinion.
I would recommend using the delimiter for Scanner see below:
Scanner s = new Scanner(foo);
s.useDelimiter(" ");
// do input stuff here

Condensing basic code using || operator with a string

I'm quite new to java programming. I was unable to find any information relating to the use of the || operator with strings. I was wondering if there was a more efficient way to do this code in particular that was still easily readable. I tried making a simple calculator as a way to familiarize myself with IfThenElse statements.
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
double first;
double second;
String option;
while(true){
System.out.println("What function would you like to calculate?");
option=input.next();
if(option.equals("add") || option.equals("+")){
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double add=first+second;
System.out.println(add);
}
else if(option.equals("subtract") || option.equals("-")) {
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double subtract=first-second;
System.out.println(subtract);
}
else if(option.equals("multiply") ||option.equals("*")) {
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double multiply=first*second;
System.out.println(multiply);
}
else if(option.equals("divide") || option.equals("/")) {
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double divide=first/second;
System.out.println(divide);
}
else if(option.equals("end")){
System.exit(0);
}
}
}
}
For the most part I am wondering about the if requirements, which I have tested and they do work, but it seems a bit clunky to me. However, any critique would be greatly appreciated.
Switch/case statements are a nice alternative to a series of ifs, and as of Java 7 you can use switch statements with strings. Note the syntactical difference between the two. Instead of grouping things with curly braces, each case ends with a break statement.
switch (option) {
case "add":
case "+":
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double add=first+second;
System.out.println(add);
break;
case "subtract":
case "-":
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double subtract=first-second;
System.out.println(subtract);
break;
case "multiply":
case "*":
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double multiply=first*second;
System.out.println(multiply);
break;
case "divide":
case "/":
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double divide=first/second;
System.out.println(divide);
break;
case "end":
System.exit(0);
}
I would then suggest combining the duplicated prompt code. If you find yourself copying and pasting code it's usually a good idea to take a step back and figure out how you can avoid the repetition. Duplicated code is a sign that you should do some refactoring.
if (option.equals("end")) {
System.exit(0);
}
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
switch (option) {
case "add":
case "+":
double add=first+second;
System.out.println(add);
break;
case "subtract":
case "-":
double subtract=first-second;
System.out.println(subtract);
break;
case "multiply":
case "*":
double multiply=first*second;
System.out.println(multiply);
break;
case "divide":
case "/":
double divide=first/second;
System.out.println(divide);
break;
}
Furthermore, you could also eliminate the duplicate printouts by using a single result variable for all of the calculations.
if (option.equals("end")) {
System.exit(0);
}
System.out.println("First number");
first=input.nextDouble();
System.out.println("Second number");
second=input.nextDouble();
double result;
switch (option) {
case "add": case "+": result = first + second; break;
case "subtract": case "-": result = first - second; break;
case "multiply": case "*": result = first * second; break;
case "divide": case "/": result = first / second; break;
}
System.out.println(result);
You're use of || seems fine to me. However I have a number of general suggestions to make the code better overall.
First of all, why not have isAdd, isSubtract, etc. functions? For example:
private boolean isAdd(String input){
return input.equalsIgnoreCase("add") || input.equals("+");
}
Same goes for the other operators. Than you can have code such as:
if (isAdd(option)) ...
Which is more readable than
if (input.equalsIgnoreCase("add") || input.equals("+")) ...
In a larger program, you might need to check these kinds of things more than once, and then having a method to do this becomes extra-handy. Also, this way if you want to change the definition of "add" (for example now "a" also qualifies), you change code in one place and the whole program complies.
Secondly, why not extract the bodies of these if statements into other functions? Than your code would read like so:
if (isAdd(option))
performAddition();
else if (isSubtract(option))
performSubtraction();
// .. etc
// function definitions here
Making for a much more readable program, as opposed to what you currently have.
Thirdly, notice where you put your spaces. option = input.next() looks better than option=input.next().
That's it pretty much. Good luck :)
John Kugelman and Aviv Cohn both gave good advice. I would like to add that your application will throw an InputMismatchException if you don't enter a valid number at the call to nextDouble(). Instead of your program terminating because of the exception you can prompt the user to enter a valid number after which he/she can try again.
One way to do this is by adding the following methods to SimpleCalculator:
private static Double getValidNumber()
{
Double nr = null;
while( nr == null )
{
nr = getNextDouble();
if(nr == null) System.out.println("Please enter a valid number.");
}
return nr;
}
private static Double getNextDouble()
{
Scanner input=new Scanner(System.in);
Double output = null;
try{ output = input.nextDouble(); }catch(InputMismatchException e){}
return output;
}
Then in your main method, simply replace the calls to input.nextDouble() by getValidNumber().

Method Miscalculation

I am having trouble understanding a calculation within my code. I have done one method for addition in this mini calculator I am making. This is purely to practice methods. I created the first method for addition and for some reason when I select the option to add two numbers together and the program goes in to the method and returns an answer it does a multiplication instead of an addition.
The code is below for the whole program:
import java.util.Scanner;
public class Testing {
/**
* #param args
*/
public static void main(String[] args) {
Scanner userReader = new Scanner(System.in);
int number1;
int number2;
int decision;
int result = 0;
System.out.println("Please input your first number");
number1 = userReader.nextInt();
System.out.println("Please input your second number");
number2 = userReader.nextInt();
System.out.println("Please select what you would like to do");
System.out.println("1.Addition");
System.out.println("2.Subtraction");
System.out.println("3.Division");
System.out.println("4.Multiplication");
decision = userReader.nextInt();
switch(decision)
{
case 1 : result = Addition(number1,number2);
case 2 : result = number1 - number2;
case 3 : result = number1 / number2;
case 4 : result = number1 * number2;
}
System.out.println("Your answer is " + result);
}
public static int Addition(int number1, int number2) {
int Additionresult;
Additionresult = number1 + number2;
return Additionresult;
}
}
Best Regards
In addition, it is good practice to add a default so that if the user enters a number other than 1, 2, 3, or 4 you can let the user know they have entered an invalid option.
Example:
switch (decision)
{
case 1:
....;
break;
case 2:
....;
break;
case 3:
....;
break;
case 4:
....;
break;
default:
System.out.println("Invalid option");
break;
}
You forgot the break after each case.

Categories

Resources