SimpleCalculator.java I need help with this program, i have no idea where to sta
ID: 3557674 • Letter: S
Question
SimpleCalculator.java
I need help with this program, i have no idea where to start. I need to have a different class for Calculator, CalculatorTest and UnknownOperatorException
Write a program that can serve as a simple calculator. This calculator keeps track of a single number (of type double) that is called result and that starts out as 0.0. Each cycle allows the user to repeatedly add, subtract, multiply, or divide by a second number. The result of one of these operations becomes the new value of result. The calculation ends when the user enters the letter R for
Explanation / Answer
//import Scanner as we require it.
import java.util.Scanner;
// the name of our class its public
public class SimpleCalculator {
//void main
public static void main (String[] args)
{
//declare int and char
int a,b,result=0;
char c;
//Declare input as scanner
Scanner input = new Scanner(System.in);
//Take inputs
System.out.println("Enter no. :");
a = input.nextInt();
System.out.println("Enter no. :");
b = input.nextInt();
System.out.println("Enter Operator :");
String st = input.next();
c = st.charAt(0);
//add a switch statement
switch(c)
{
case '+':
result = a+b;
System.out.println("Result = "+result);
break;
case '-':
result = a-b;
System.out.println("Result = "+result);
break;
case 'x':
result = a*b;
System.out.println("Result = "+result);
break;
case '/':
result = a/b;
System.out.println("Result = "+result);
break;
default:
System.out.println("Syntax Error");
}
}
}
Output
Enter no. :
12
Enter no. :
54
Enter Operator :
x
Result = 648
How does it work
Extending it
The program can be extended. You can use more numbers or other functions of calculator like square, root,trigonometry, etc to expand it. Go ahead
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.