C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Java programs » Java basic programs

In this java program, we are writing code for a simple calculator. Here, we are performing multiple basic mathematical tasks using switch case statement and do while loop. Submitted by IncludeHelp, on November 19, 2017

Given numbers and we have to perform mathematical operations using java program.

Here, we have following operations to be performed through this program,

Program will run infinite times until we do not press the 5 (a user choice).

import java.util.Scanner; public class Calculator { public static void main(String args[]) { // declare here float a,b,res; char choice, ch; Scanner S=new Scanner(System.in); do { // prepare menu for the user to see multiple operations. System.out.println("\n\nMain Menu : \n1.Addition\n2.Subtraction\n3.Division\n4.Multiplication\n5.Exit\n"); // enter the choice System.out.print("Enter your choice : "); // read the input choice value. choice=S.next().charAt(0); // this loop will calculate different the operations value at different dofferent values. switch(choice) { case '1':System.out.print("Enter two numbers : "); a=S.nextFloat(); b=S.nextFloat(); res=a+b; System.out.print("Result : " +res); break; case '2':System.out.print("Enter two numbers : "); a=S.nextFloat(); b=S.nextFloat(); res=a-b; System.out.print("Result : " +res); break; case '3':System.out.print("Enter two numbers : "); a=S.nextFloat(); b=S.nextFloat(); res=a/b; System.out.print("Result : " +res); break; case '4':System.out.print("Enter two numbers : "); a=S.nextFloat(); b=S.nextFloat(); res=a*b; System.out.print("Result : " +res); break; case '5': System.exit(0); break; default : System.out.print("Wrong Choice.....\n"); break; } } // loop works till the number 5 not selected. while(choice!=5); } }

Output

Main Menu : 1.Addition 2.Subtraction 3.Division 4.Multiplication 5.Exit Enter your choice : 1 Enter two numbers : 2 5 Result : 7.0 Main Menu : 1.Addition 2.Subtraction 3.Division 4.Multiplication 5.Exit Enter your choice : 2 Enter two numbers : 8 6 Result : 2.0 Main Menu : 1.Addition 2.Subtraction 3.Division 4.Multiplication 5.Exit Enter your choice : 3 Enter two numbers : 10 2 Result : 5.0 Main Menu : 1.Addition 2.Subtraction 3.Division 4.Multiplication 5.Exit Enter your choice : 4 Enter two numbers : 5 5 Result : 25.0 Main Menu : 1.Addition 2.Subtraction 3.Division 4.Multiplication 5.Exit Enter your choice : 5

Liked this article? Do share with your friends :)

C, C++, Java, D.S., Python, .Net, SQL, PL/SQL, Ajax, PHP, JavaScript, CSS, HTML, C programs, C++ programs, Java programs, C# programs, DS programs, C aptitude, C++ aptitude, Java aptitude, DBMS aptitude, O.S., Networking, Embedded systems, Nanotechnologies, Linux, DOS, puzzles, syntaxes,