Computers
View Answers
May 1, 2008 at 6:53 PM
Hi,
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
class CalcFrame extends Frame {
CalcFrame( String str) {
// call to superclass
super(str);
// to close the calculator(Frame)
addWindowListener(new WindowAdapter() {
public void windowClosing (WindowEvent we) {
System.exit(0);
}
});
}
}
public class Calculator implements ActionListener, ItemListener {
// creating instances of objects
CalcFrame fr;
MenuBar menu;
Menu view, font;
MenuItem bold, regular;
CheckboxMenuItem basic ;
CheckboxGroup cbg;
Checkbox radians, degrees;
TextField display;
Button key[] = new Button[20]; // creates a button object array of 20
Button clearAll, clearEntry, round;
Button scientificKey[] = new Button[10]; // creates a button array of 8
// declaring variables
boolean addButtonPressed, subtractButtonPressed, multiplyButtonPressed;
boolean divideButtonPressed, decimalPointPressed, powerButtonPressed;
boolean roundButtonPressed = false;
double initialNumber; // the first number for the two number operation
double currentNumber = 0; // the number shown in the screen while it is being pressed
int decimalPlaces = 0;
// main function
public static void main (String args[]) {
// constructor
Calculator cal = new Calculator();
cal.makeCalculator();
}
public void makeCalculator() {
// size of the button
final int BWIDTH = 25;
final int BHEIGHT = 25;
int count =1;
// create frame for the calculator
fr = new CalcFrame("Simple Calculator");
// set the size
fr.setSize(300,270);
fr.setBackground(Color.pink);;
// create a menubar for the frame
menu = new MenuBar();
// add menu the menubar
view = new Menu("View");
font = new Menu ("Font");
// create instance of object for View menu
basic = new CheckboxMenuItem("Basic",true);
// add a listener to receive item events when the state of an item changes
basic.addItemListener(this);
// create instance of object for font menu
bold = new MenuItem("Arial Bold");
bold.addActionListener(this);
regular = new MenuItem("Arial Regular");
regular.addActionListener(this);
view.add(basic);
font.add(bold);
font.add(regular);
// add the menus in the menubar
menu.add(view);
menu.add(font);
// add menubar to the frame
fr.setMenuBar(menu);
// override the layout manager
fr.setLayout(null);
// set the initial numbers that is 1 to 9
for (int row = 0; row < 3; ++row) {
for (int col = 0; col < 3; ++col) {
// this will set the key from 1 to 9
key[count] = new Button(Integer.toString(count));
key[count].addActionListener(this);
// set the boundry for the keys
key[count].setBounds(30*(col + 1), 30*(row + 4),BWIDTH,BHEIGHT);
key[count].setBackground(Color.yellow);
// add to the frame
fr.add(key[count++]);
}
}
May 1, 2008 at 6:56 PM
// Now create, addlistener and add to frame all other keys
key[0] = new Button("0");
key[0].addActionListener(this);
key[0].setBounds(30,210,BWIDTH,BHEIGHT);
key[0].setBackground(Color.yellow);
fr.add(key[0]);
//decimal
key[10] = new Button(".");
key[10].addActionListener(this);
key[10].setBounds(60,210,BWIDTH,BHEIGHT);
key[10].setBackground(Color.yellow);
fr.add(key[10]);
//equals to
key[11] = new Button("=");
key[11].addActionListener(this);
key[11].setBounds(90,210,BWIDTH,BHEIGHT);
key[11].setBackground(Color.yellow);
fr.add(key[11]);
//multiply
key[12] = new Button("*");
key[12].addActionListener(this);
key[12].setBounds(120,120,BWIDTH,BHEIGHT);
key[12].setBackground(Color.yellow);
fr.add(key[12]);
//divide
key[13] = new Button("/");
key[13].addActionListener(this);
key[13].setBounds(120,150,BWIDTH,BHEIGHT);
key[13].setBackground(Color.yellow);
fr.add(key[13]);
//addition
key[14] = new Button("+");
key[14].addActionListener(this);
key[14].setBounds(120,180,BWIDTH,BHEIGHT);
key[14].setBackground(Color.yellow);
fr.add(key[14]);
//subtract
key[15] = new Button("-");
key[15].addActionListener(this);
key[15].setBounds(120,210,BWIDTH,BHEIGHT);
key[15].setBackground(Color.yellow);
fr.add(key[15]);
//reciprocal
key[16] = new Button("1/x");
key[16].addActionListener(this);
key[16].setBounds(150,120,BWIDTH,BHEIGHT);
key[16].setBackground(Color.yellow);
fr.add(key[16]);
//power
key[17] = new Button("x^n");
key[17].addActionListener(this);
key[17].setBounds(150,150,BWIDTH,BHEIGHT);
key[17].setBackground(Color.yellow);
fr.add(key[17]);
//change sign
key[18] = new Button("+/-");
key[18].addActionListener(this);
key[18].setBounds(150,180,BWIDTH,BHEIGHT);
key[18].setBackground(Color.yellow);
fr.add(key[18]);
//factorial
key[19] = new Button("x!");
key[19].addActionListener(this);
key[19].setBounds(150,210,BWIDTH,BHEIGHT);
key[19].setBackground(Color.yellow);
fr.add(key[19]);
// CA
clearAll = new Button("CA");
clearAll.addActionListener(this);
clearAll.setBounds(30, 240, BWIDTH+20, BHEIGHT);
clearAll.setBackground(Color.yellow);
fr.add(clearAll);
// CE
clearEntry = new Button("CE");
clearEntry.addActionListener(this);
clearEntry.setBounds(80, 240, BWIDTH+20, BHEIGHT);
clearEntry.setBackground(Color.yellow);
fr.add(clearEntry);
// round
round = new Button("Round");
round.addActionListener(this);
round.setBounds(130, 240, BWIDTH+20, BHEIGHT);
round.setBackground(Color.yellow);
fr.add(round);
// set display area
display = new TextField("0");
display.setBounds(30,90,150,20);
display.setBackground(Color.white);
May 1, 2008 at 6:56 PM
cbg = new CheckboxGroup();
degrees = new Checkbox("Degrees", cbg, true);
radians = new Checkbox("Radians", cbg, false);
degrees.addItemListener(this);
radians.addItemListener(this);
degrees.setBounds(185, 75, 3 * BWIDTH, BHEIGHT);
radians.setBounds(185, 95, 3 * BWIDTH, BHEIGHT);
degrees.setVisible(false);
radians.setVisible(false);
fr.add(degrees);
fr.add(radians);
fr.add(display);
fr.setVisible(true);
} // end of makeCalculator
public void actionPerformed(ActionEvent ae) {
String buttonText = ae.getActionCommand();
double displayNumber = Double.valueOf(display.getText()).doubleValue();
// if the button pressed text is 0 to 9
if((buttonText.charAt(0) >= '0') & (buttonText.charAt(0) <= '9')) {
if(decimalPointPressed) {
for (int i=1;i <=decimalPlaces; ++i)
currentNumber *= 10;
currentNumber +=(int)buttonText.charAt(0)- (int)'0';
for (int i=1;i <=decimalPlaces; ++i) {
currentNumber /=10;
}
++decimalPlaces;
display.setText(Double.toString(currentNumber));
}
else if (roundButtonPressed) {
int decPlaces = (int)buttonText.charAt(0) - (int)'0';
for (int i=0; i< decPlaces; ++i)
displayNumber *=10;
displayNumber = Math.round(displayNumber);
for (int i = 0; i < decPlaces; ++i) {
displayNumber /=10;
}
display.setText(Double.toString(displayNumber));
roundButtonPressed = false;
}
else {
currentNumber = currentNumber * 10 + (int)buttonText.charAt(0)-(int)'0';
display.setText(Integer.toString((int)currentNumber));
}
}
May 1, 2008 at 6:57 PM
if(buttonText == "+") {
addButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}
// if button pressed is subtract
if (buttonText == "-") {
subtractButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}
// if button pressed is divide
if (buttonText == "/") {
divideButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}
// if button pressed is multiply
if (buttonText == "*") {
multiplyButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}
// if button pressed is reciprocal
if (buttonText == "1/x") {
// call reciprocal method
display.setText(reciprocal(displayNumber));
currentNumber = 0;
decimalPointPressed = false;
}
// if button is pressed to change a sign
if (buttonText == "+/-") {
// call changesign meyhod to change the sign
display.setText(changeSign(displayNumber));
currentNumber = 0;
decimalPointPressed = false;
}
// factorial button
if (buttonText == "x!") {
display.setText(factorial(displayNumber));
currentNumber = 0;
decimalPointPressed = false;
}
// power button
if (buttonText == "x^n") {
powerButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}
May 1, 2008 at 6:58 PM
// this will convert the numbers displayed to degrees
if (buttonText == "todeg")
display.setText(Double.toString(Math.toDegrees(displayNumber)));
// this will convert the numbers displayed to radians
if (buttonText == "torad")
display.setText(Double.toString(Math.toRadians(displayNumber)));
if (buttonText == "Pi") {
display.setText(Double.toString(Math.PI));
currentNumber =0;
decimalPointPressed = false;
}
if (buttonText == "Round")
roundButtonPressed = true;
// check if decimal point is pressed
if (buttonText == ".") {
String displayedNumber = display.getText();
boolean decimalPointFound = false;
int i;
decimalPointPressed = true;
// check for decimal point
for (i =0; i < displayedNumber.length(); ++i) {
if(displayedNumber.charAt(i) == '.') {
decimalPointFound = true;
continue;
}
}
if (!decimalPointFound)
decimalPlaces = 1;
}
if(buttonText == "CA"){
// set all buttons to false
resetAllButtons();
display.setText("0");
currentNumber = 0;
}
if (buttonText == "CE") {
display.setText("0");
currentNumber = 0;
decimalPointPressed = false;
}
if (buttonText == "E") {
display.setText(Double.toString(Math.E));
currentNumber = 0;
decimalPointPressed = false;
}
May 1, 2008 at 6:59 PM
// the main action
if (buttonText == "=") {
currentNumber = 0;
// if add button is pressed
if(addButtonPressed)
display.setText(Double.toString(initialNumber + displayNumber));
// if subtract button is pressed
if(subtractButtonPressed)
display.setText(Double.toString(initialNumber - displayNumber));
// if divide button is pressed
if (divideButtonPressed) {
// check if the divisor is zero
if(displayNumber == 0) {
MessageBox mb = new MessageBox ( fr, "Error ", true, "Cannot divide by zero.");
mb.show();
}
else
display.setText(Double.toString(initialNumber/displayNumber));
}
// if multiply button is pressed
if(multiplyButtonPressed)
display.setText(Double.toString(initialNumber * displayNumber));
// if power button is pressed
if (powerButtonPressed)
display.setText(power(initialNumber, displayNumber));
// set all the buttons to false
resetAllButtons();
}
if (buttonText == "Arial Regular") {
for (int i =0; i < 10; ++i)
key[i].setFont(new Font("Arial", Font.PLAIN, 12));
}
if (buttonText == "Arial Bold") {
for (int i =0; i < 10; ++i)
key[i].setFont(new Font("Arial", Font.BOLD, 12));
}
} // end of action events
public void itemStateChanged(ItemEvent ie){
if (ie.getItem() == "Basic") {
basic.setState(true);
// scientific.setState(false);
fr.setTitle("Basic Calculator Example");
fr.setSize(200,270);
// check if the scientific keys are visible. if true hide them
if (scientificKey[0].isVisible()) {
for (int i=0; i < 8; ++i)
scientificKey[i].setVisible(false);
radians.setVisible(false);
degrees.setVisible(false);
}
}
} // end of itemState
May 1, 2008 at 7:00 PM
public void resetAllButtons() {
addButtonPressed = false;
subtractButtonPressed = false;
multiplyButtonPressed = false;
divideButtonPressed = false;
decimalPointPressed = false;
powerButtonPressed = false;
roundButtonPressed = false;
}
public String factorial(double num) {
int theNum = (int)num;
if (theNum < 1) {
MessageBox mb = new MessageBox (fr, "Facorial Error", true,
"Cannot find the factorial of numbers less than 1.");
mb.show();
return("0");
}
else {
for (int i=(theNum -1); i > 1; --i)
theNum *= i;
return Integer.toString(theNum);
}
}
public String reciprocal(double num) {
if (num ==0) {
MessageBox mb = new MessageBox(fr,"Reciprocal Error", true,
"Cannot find the reciprocal of 0");
mb.show();
}
else
num = 1/num;
return Double.toString(num);
}
public String power (double base, double index) {
return Double.toString(Math.pow(base, index));
}
public String changeSign(double num) {
return Double.toString(-num);
}
}
class MessageBox extends Dialog implements ActionListener {
Button ok;
MessageBox(Frame f, String title, boolean mode, String message) {
super(f, title, mode);
Panel centrePanel = new Panel();
Label lbl = new Label(message);
centrePanel.add(lbl);
add(centrePanel, "Center");
Panel southPanel = new Panel();
ok = new Button ("OK");
ok.addActionListener(this);
southPanel.add(ok);
add(southPanel, "South");
pack();
addWindowListener (new WindowAdapter(){
public void windowClosing (WindowEvent we) {
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae) {
dispose();
}
}
-------------------------
read for more information,
http://www.roseindia.net/java/
Related Tutorials/Questions & Answers:
computers - Java Beginnerscomputers Describe any 5 methods in any of the library classes of java? Hi Friend,
Please visit the following link:
http://www.roseindia.net/java/java-get-example/index.shtml
Here you will get lot
Advertisements
E Book Witing Ebook writing
eBook Writing
As
computers are gaining control of the world, the
trend of paper books is out and that of eBooks are
sweeping
Java UDP
Java UDP
TCP and UDP are transport protocols used for communication between
computers.
UDP(User Datagram Protocol) is a very simple connectionless protocol. UDP can
EBook Witing eBook Writing
As
computers are gaining control of the world, the trend of
paper books is out and that of eBooks are sweeping in.
Writing and publishing eBooks has become hugely popular
amongst writers
Domain NameThe domain name system (DNS) is a series of letters and numbers that are separated by periods and used to name organizations,
computers and addresses on the Internet. The domain name is the way that Internet names are located
The Open Source World is a Big Part of PHPThe PHP scripting language is something that can work on many types of
computers and can be used alongside HTML. It is also able to work with a variety of different forms of technology. The big reason for this comes from how PHP is an open
What is ASCII? characters in most of
the
computers that can be displayed on the computer screen...
computers. IBM
has its own built-in-code called EBCDIC code containing 256
What is Mobile WebsiteWhat is Mobile Website
Mobile websites are specially designed for viewing
mobile contents on Mobile Phones. Earlier websites were
seen only on
computers... very slower
speed. So websites for
computers cannot function well on
mobile
ASCII values tableASCII values table
ASCII stands for American Standard Code for
Information Interchange.
Computers can only understand numbers, so an ASCII
PHP Is Great for Website CreationPHP is one of the most commonly used and understood types of website creation scripts in the world. It is being used by all sorts of different
computers and is being loaded onto many servers. Here are some reasons why PHP is so great
Java for complete beginnersJava Guide is available at RoseIndia that help beginners to master the
language. Because of its usefulness in both software development for
computers
and application development for mobile phone, Java is in great demand and so
Work Email- Dos and Don?ts
Work Email- Dos and Don’ts
Introduction
With the proliferation of
computers... of
computers, it is very easy to type out everything you feel onto the screen
Remote Desktop Setting in Windows 8In windows 8 operating system you can easily access other
computers inside the network by enabling the Remote Desktop Connection in your
PC.
1..._TO_REPLACE_4
5. Mark the 'Allow connections only from
computers
running Remote
Windows 8 Operating SystemWindows 8 is the latest innovation, which has been launched to make easy handling of the Windows operating system. Launched by the Microsoft it is expected to make easier for the use on personal
computers and also for home and business
What is procedureWhat is procedure What is procedure in
computers? What are the primary categories of procedures
jade technologyjade technology 1)how message is passed using jade technology ?
2)how LAN (local area network) is established between two
computers jade technologyjade technology 1)how message is passed using jade technology ?
2)how LAN (local area network) is established between two
computers jade technologyjade technology 1)how message is passed using jade technology ?
2)how LAN (local area network) is established between two
computers How do i slow down the game (othello game)?? an othello game that can be played by 2 humans , human and computer and two
computers.
Everything works correctly but the problem is that when 2
computers play... the 2
computers is very fast, for that i tried to use the timer but it give me
Java Image Browsing AppletJava Image Browsing Applet Hi.
I want to create an applet which is embedded in html page which display image by browsing the files in the
computers hard disk...
Please help me out
advantage of stored programsadvantage of stored programs Which of the following is an advantage of stored programs?
a) Reliability
b)Reduction in operation costs
c) The
computers becoming general purpose
D) All of the above
E) None of these
where are program instructions and data values storedwhere are program instructions and data values stored Where are program instructions and data values stored in Computer?
In Storage. Actually, whichever program and data we use in our
computers are stored in Storage
GIGO Full FormGIGO Full Form What is Full form of GIGO?
Garbage In, Garbage Out is a Full Form of GIGO in regards simple principles followed by
computers What is hacker?What is hacker? What is hacker?
A Hacker is a person who used his or her expertise to gain access to other people's
computers to get information illegally or do damage
Remote System OS name in JAVA - JSP-ServletRemote System OS name in JAVA I need to print the different os names of the all
computers in my local network. I know that with System.getProperty("os.name"), I get the os name of my computer but for the other
computers, I have
Proxies, it is advanced traffic redirection tool. It can provide you access to
computers behind..., it is advanced traffic redirection tool. It can provide you access to
computers behind
Computer Networking the requirement to add more people as well more
computers.
Suppose you buy 5
computers... by the new 5
computers, this will save the
money and resources to buy... a network in which all the
computers are
interconnected and share the same printer
Computer Networking the requirement to add more people as well more
computers.
Suppose you buy 5
computers instead of going for a decision to buy 5 more
printers, you... printer by the new 5
computers, this will save the
money and resources
Question In the Network ? currently has 25 standalone
computers and five laser printers
distributed... the laser printers, but the
computers donā??t connect to each other.
Because.... The company founder, Joe, things that all the
computers should be able to communicate
computer - Swing AWTcomputer What is a Computer and why we should use it? I am new to this technologies so please let me know the benefits of using computer. What you what to know about
computers?Is it a software or hardware related
javajava hi..i have developed a desktop application and i want it to run in other
computers also which are connected through LAN.is it possible to do so??all the database must be in master computer only and all other computer must
digital communication systemdigital communication system A digital communication system capable of interconnecting, a large number of
computers, terminals and other peripheral devices within a limited geographical area is called-
a) LAN,
B) WAN,
C
Welcome to the Internet be used for standard intercommunication and file transfer between
computers... is passed by both the
computers using the TCP/IP protocol. This means that
the IP addresses will be assigned to both the
computers.
Then using the HTTP protocol