Mycalculator
Mycalculator
Javatpoint Logo
Custom Search
Home
Java
C
C++
C#
Servlet
JSP
EJB
Struts2
Mail
Hibernate
Spring
Android
Design P
Quiz
Projects
Interview Q
Comment
Forum
Training
Basics of Java
OOPs Concepts
Java String
Java Regex
Exception Handling
Java Inner classes
Java Multithreading
Java I/O
Java Networking
Java AWT & Events
Java Swing
Swing IntroductionJava JButtonJava JLabelJava JTextFieldJava JTextAreaJava
JPasswordFieldJava JCheckBoxJava JRadioButtonJava JComboBoxJava JTableJava
JListJava JOptionPaneJava JScrollBarJava JMenuItem & JMenuJava JPopupMenuJava
JCheckBoxMenuItemJava JSeparatorJava JProgressBarJava JTreeJava JColorChooserJava
JTabbedPaneJava JSliderJava JSpinnerJava JDialogJava JPanelJava JFileChooserJava
JToggleButtonJava JToolBarJava JViewportJava JFrameJava JComponentJava
JLayeredPaneJava JDesktopPaneJava JEditorPaneJava JScrollPaneJava JSplitPaneJava
JTextPaneJava JRootPaneUsing ToolTipChange Title IconExecutable Jar FileDigital
WatchGraphics in swingDisplaying Image
Java Swing Apps
NotepadCalculatorIP FinderWord CounterURL Source GeneratorFolder ExplorerPuzzle
GamePic Puzzle GameTic Tac Toe GameOnline Exam
LayoutManagers
BorderLayoutGridLayoutFlowLayoutBoxLayoutCardLayoutGridBagLayoutGroupLayoutSpringLa
youtScrollPaneLayout
JavaFX
Java Applet
Java Reflection
Java Date
Java Conversion
Java Collection
Java JDBC
Java New Features
RMI
Internationalization
Interview Questions
JavaTpoint
next ??prev
Calculator in Java with Source Code
Calculator in Java with Source Code: We can develop calculator in java with the
help of AWT/Swing with event handling. Let's see the code of creating calculator in
java.
/*********************************************
Save this file as MyCalculator.java
to compile it use
javac MyCalculator.java
to use the calcuator do this
java MyCalculator
**********************************************/
import java.awt.*;
import java.awt.event.*;
/*********************************************/
String digitButtonText[] = {"7", "8", "9", "4", "5", "6", "1", "2", "3", "0",
"+/-", "." };
String operatorButtonText[] = {"/", "sqrt", "*", "%", "-", "1/X", "+", "=" };
String memoryButtonText[] = {"MC", "MR", "MS", "M+" };
String specialButtonText[] = {"Backspc", "C", "CE" };
memoryButton[i].setForeground(Color.RED);
y+=HEIGHT+V_SPACE;
}
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{System.exit(0);}
});
setLayout(null);
setSize(FRAME_WIDTH,FRAME_HEIGHT);
setVisible(true);
}
//////////////////////////////////
static String getFormattedText(double temp)
{
String resText=""+temp;
if(resText.lastIndexOf(".0")>0)
resText=resText.substring(0,resText.length()-2);
return resText;
}
////////////////////////////////////////
public static void main(String []args)
{
new MyCalculator("Calculator - JavaTpoint");
}
}
/*******************************************/
//////////////////////////////////////////
MyDigitButton(int x,int y, int width,int height,String cap, MyCalculator clc)
{
super(cap);
setBounds(x,y,width,height);
this.cl=clc;
this.cl.add(this);
addActionListener(this);
}
////////////////////////////////////////////////
static boolean isInString(String s, char ch)
{
for(int i=0; i<s.length();i++) if(s.charAt(i)==ch) return true;
return false;
}
/////////////////////////////////////////////////
public void actionPerformed(ActionEvent ev)
{
String tempText=((MyDigitButton)ev.getSource()).getLabel();
if(tempText.equals("."))
{
if(cl.setClear)
{cl.displayLabel.setText("0.");cl.setClear=false;}
else if(!isInString(cl.displayLabel.getText(),'.'))
cl.displayLabel.setText(cl.displayLabel.getText()+".");
return;
}
int index=0;
try{
index=Integer.parseInt(tempText);
}catch(NumberFormatException e){return;}
if(cl.setClear)
{cl.displayLabel.setText(""+index);cl.setClear=false;}
else
cl.displayLabel.setText(cl.displayLabel.getText()+index);
}//actionPerformed
}//class defination
/********************************************/
cl.setClear=true;
double temp=Double.parseDouble(cl.displayLabel.getText());
if(opText.equals("1/x"))
{
try
{double tempd=1/(double)temp;
cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0.");}
return;
}
if(opText.equals("sqrt"))
{
try
{double tempd=Math.sqrt(temp);
cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0.");}
return;
}
if(!opText.equals("="))
{
cl.number=temp;
cl.op=opText.charAt(0);
return;
}
// process = button pressed
switch(cl.op)
{
case '+':
temp+=cl.number;break;
case '-':
temp=cl.number-temp;break;
case '*':
temp*=cl.number;break;
case '%':
try{temp=cl.number%temp;}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0."); return;}
break;
case '/':
try{temp=cl.number/temp;}
catch(ArithmeticException excp)
{cl.displayLabel.setText("Divide by 0."); return;}
break;
}//switch
cl.displayLabel.setText(MyCalculator.getFormattedText(temp));
//cl.number=temp;
}//actionPerformed
}//class
/****************************************/
/////////////////////////////////
MyMemoryButton(int x,int y, int width,int height,String cap, MyCalculator clc)
{
super(cap);
setBounds(x,y,width,height);
this.cl=clc;
this.cl.add(this);
addActionListener(this);
}
////////////////////////////////////////////////
public void actionPerformed(ActionEvent ev)
{
char memop=((MyMemoryButton)ev.getSource()).getLabel().charAt(1);
cl.setClear=true;
double temp=Double.parseDouble(cl.displayLabel.getText());
switch(memop)
{
case 'C':
cl.memLabel.setText(" ");cl.memValue=0.0;break;
case 'R':
cl.displayLabel.setText(MyCalculator.getFormattedText(cl.memValue));break;
case 'S':
cl.memValue=0.0;
case '+':
cl.memValue+=Double.parseDouble(cl.displayLabel.getText());
if(cl.displayLabel.getText().equals("0") ||
cl.displayLabel.getText().equals("0.0") )
cl.memLabel.setText(" ");
else
cl.memLabel.setText("M");
break;
}//switch
}//actionPerformed
}//class
/*****************************************/
//////////////////////////////////////////////////////////
public void actionPerformed(ActionEvent ev)
{
String opText=((MySpecialButton)ev.getSource()).getLabel();
//check for backspace button
if(opText.equals("Backspc"))
{
String tempText=backSpace(cl.displayLabel.getText());
if(tempText.equals(""))
cl.displayLabel.setText("0");
else
cl.displayLabel.setText(tempText);
return;
}
//check for "C" button i.e. Reset
if(opText.equals("C"))
{
cl.number=0.0; cl.op=' '; cl.memValue=0.0;
cl.memLabel.setText(" ");
}
/*********************************************
Features not implemented and few bugs
? prevnext ?
Tally Tutorial
Tally
Godot Tutorial
Godot
Gradle Tutorial
Gradle
UML Tutorial
UML
ES6 Tutorial
ES6
Flutter Tutorial
Flutter
Selenium Python
Selenium Py
Firebase Tutorial
Firebase
Cobol Tutorial
Cobol
Preparation
Aptitude
Aptitude
Logical Reasoning
Reasoning
Verbal Ability
Verbal A.
Interview Questions
Interview
Trending Technologies
Artificial Intelligence Tutorial
AI
AWS Tutorial
AWS
Selenium tutorial
Selenium
Cloud tutorial
Cloud
Hadoop tutorial
Hadoop
ReactJS Tutorial
ReactJS
Angular 7 Tutorial
Angular 7
Blockchain Tutorial
Blockchain
Git Tutorial
Git
DevOps Tutorial
DevOps
B.Tech / MCA
DBMS tutorial
DBMS
DAA tutorial
DAA
html tutorial
Web Tech.
Automata Tutorial
Automata
C Language tutorial
C
C++ tutorial
C++
Java tutorial
Java
Python tutorial
Python
List of Programs
Programs
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on [email protected], to
get more information about given services.
Website Designing
Website Development
Java Development
PHP Development
WordPress
Graphic Designing
Logo
Digital Marketing
On Page and Off Page SEO
PPC
Content Development
Corporate Training
Classroom and Online Training
Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net,
Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at
[email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email
Alerts Facebook Page Twitter Page YouTube Blog Page
LEARN TUTORIALS
Learn Java
Learn Data Structures
Learn C Programming
Learn C++ Tutorial
Learn C# Tutorial
Learn PHP Tutorial
Learn HTML Tutorial
Learn JavaScript Tutorial
Learn jQuery Tutorial
Learn Spring Tutorial
OUR WEBSITES
Javatpoint.com
Hindi100.com
Lyricsia.com
Quoteperson.com
Jobandplacement.com
OUR SERVICES
Website Development
Android Development
Website Designing
Digital Marketing
Summer Training
Industrial Training
CONTACT
Address: G-13, 2nd Floor, Sec-3
Contact Us
Subscribe Us
Privacy Policy
Sitemap
About Me
� Copyright 2011-2018 www.javatpoint.com. All rights reserved. Developed by
JavaTpoint.