Learn to code calculator in java for beginners

Prerequisite

Java

To develop and run any java program you need to install Java in your system. You can download the latest version of Java for Windows/ Mac/ Linux/ Solaris from here. For more detailed steps, please visit this page.

IntelliJ IDE

After downloading Java, you need to download an IDE. I personally prefer IntelliJ IDEA because it provides to its users over alternative solutions such as text editors or open-source IDEs: Higher developer productivity, enhanced developer focus, reduced technical debt, increased testing and debugging productivity and improved testing plans. To get access to IntelliJ IDEA, go to this page and download its community version, run the set up and finish installing it.

Code

package com.company;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Calculator {
public static void main(String[] args) {
// write your code here
int a, b;
char opr;
char choice;
boolean n = true;
while (n = true) {
System.out.println("enter first number");
Scanner scan = new Scanner(System.in);
a = scan.nextInt();
System.out.println("enter second number");
b = scan.nextInt();
System.out.println("enter the operation you want to perform");
opr = scan.next().charAt(0);
switch (opr) {
case '+':
System.out.println(a + b);
break;
case '-':
System.out.println(a – b);
break;
case 'X':
System.out.println(a * b);
break;
case '/':
System.out.println(a / b);
break;
default:
System.out.println("operation is invalid");
break;
}
System.out.println("Do you want to continue? Y/N");
choice = scan.next().charAt(0);
if (choice == 'Y'|| choice== 'y')
continue;
if(choice== 'N' || choice== 'n')
break;
}
}
}
view raw Calculator.java hosted with ❤ by GitHub

Explanation

Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings from the console.

Running the code


Feel free to post queries.

One thought on “Learn to code calculator in java for beginners

  1. Thanks a lot.
    The coding over here is easy and simple. Helped a lot on my school project . It would be a great help if you can teach stacks and arrays too .

    Like

Leave a comment

Design a site like this with WordPress.com
Get started