Write a Java program that simulates a very simple, but unconventional, calculato
ID: 3902097 • Letter: W
Question
Write a Java program that simulates a very simple, but unconventional, calculator. The application’s GUI should include two text fields F1 and F2 for numerical input and a label
for output. So, to compute 23 + 56, a user enters 23 into F1 and 56 into F2. There should be four buttons labeled +, ?, * , and /. When button B is pressed, the operation (F1) B (F2) is
computed and the result displayed on the label. If a button is pressed and a field F1 or F2 is empty then the program should display an error message.
Include a button that copies the result of the computation to F1 and another that copies the result to F2. These buttons facilitate subsequent computation using the result of the previous
computation.
A Quit button ends the program.
Explanation / Answer
import java.awt.*;
import java.awt.event.*;
class chegg implements ActionListener //actionlistener interface is implemented here
{
//Declaring Objects
Frame f=new Frame();
Label l1=new Label("First Number");
Label l2=new Label("Second Number");
Label l3=new Label("Result");
TextField t1=new TextField();
TextField t2=new TextField();
TextField t3=new TextField();
Button b1=new Button("+");
Button b2=new Button("-");
Button b3=new Button("*");
Button b4=new Button("/");
Button b5=new Button("Quit");
chegg()
{
//Giving Coordinates
l1.setBounds(50,100,100,20);
l2.setBounds(50,140,100,20);
l3.setBounds(50,180,100,20);
t1.setBounds(200,100,100,20);
t2.setBounds(200,140,100,20);
t3.setBounds(200,180,100,20);
b1.setBounds(50,250,50,20);
b2.setBounds(110,250,50,20);
b3.setBounds(170,250,50,20);
b4.setBounds(230,250,50,20);
b5.setBounds(290,250,50,20);
//Adding components to the frame
f.add(l1);
f.add(l2);
f.add(l3);
f.add(t1);
f.add(t2);
f.add(t3);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
f.setLayout(null);
f.setVisible(true); //we can see the window on the monitor
f.setSize(400,350);
}
public void actionPerformed(ActionEvent e)
{
int n1=Integer.parseInt(t1.getText()); //getting input as integer
int n2=Integer.parseInt(t2.getText());//getting input as integer
if(e.getSource()==b1)
{
t3.setText(String.valueOf(n1+n2));
}
if(e.getSource()==b2)
{
t3.setText(String.valueOf(n1-n2));
}
if(e.getSource()==b3)
{
t3.setText(String.valueOf(n1*n2));
}
if(e.getSource()==b4)
{
t3.setText(String.valueOf(n1/n2));
}
if(e.getSource()==b5)
{
System.exit(0);
}
}
public static void main(String args[])
{
new chegg();
}
}
Comment below if you have any doubt
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.