Computer Applications
Java Calculator Program: Write a calculator program in Java that takes as input two numbers and a mathematical operator to perform mathematical operation and prints the calculated result. Based on the operator entered, perform the calculation, that is, '+' for addition, '-' for subtraction, '*' for product and '/' for division. For operators other than these, print the message "INVALID OPERATOR". (Make use of switch-case construct).
Answer
import java.util.Scanner;
public class KboatCalculator
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter first number: ");
int a = in.nextInt();
System.out.println("Enter second number: ");
int b = in.nextInt();
System.out.println("Enter operator: ");
char op = in.next().charAt(0);
int r = 0;
switch (op) {
case '+':
r = a + b;
System.out.println(a + " + " + b + " = " + r);
break;
case '-':
r = a - b;
System.out.println(a + " - " + b + " = " + r);
break;
case '*':
r = a * b;
System.out.println(a + " * " + b + " = " + r);
break;
case '/':
r = a / b;
System.out.println(a + " / " + b + " = " + r);
break;
default:
System.out.println("INVALID OPERATOR");
}
}
}Output
Related Questions
Which of the following is not true with regards to a switch statement?
- checks for an equality between the input and the case labels
- supports floating point constants
- break is used to exit from the switch block
- case labels are unique
A triangle is said to be an 'Equable Triangle', if the area of the triangle is equal to its perimeter. Write a program to enter three sides of a triangle. Check and print whether the triangle is equable or not.
For example, a right angled triangle with sides 5, 12 and 13 has its area and perimeter both equal to 30.Write a Java program to print name, purchase amount and final payable amount after discount as per given table:
Purchase Amount Discount upto ₹10000/- 15% ₹10000 to ₹ 20000/- 20% Above ₹20000/- 30% The statement that brings the control back to the calling method is:
- break
- System.exit(0)
- continue
- return