Question

This Java program is giving me a good amount of trouble. Can someone solve this for...

This Java program is giving me a good amount of trouble. Can someone solve this for me and provide explanations? I use BlueJ.

Create a class named DLD_JFrame_Arithmetic with a JFrame that accepts two numbers. It is the first time we will use numbers with a JFrame. JTextFields take all inputs as Strings. They must be converted.  int num = Integer.parseInt(number.getText()); We will create Three JLabels, two which prompt user to enter numbers in the JTextFields. The third will be for output. We will need two JTextFields, one for each number entered. We will need four JButtons. A button for each Add, Subtract, Multiply, and Divide. Each button will perform what its text says. Remember also, dividing by zero is an error, so you must account for it with an if statement.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Dear Student,

Thanks for posting an interesting question of Java Programming language where you want to create a simple calculator application using Java Swing.

1. For the given question I have created a complete class named as DLD_JFrame_Arithmetic with proper comments to each of the line of the code and saved the file named as DLD_JFrame_Arithmetic.java at D:/.

2. Please find below screenshot of DLD_JFrame_Arithmetic.java file contents with proper comments to each of the line of the code:-

DaWN import java.awt.event. ActionEvent; import java.awt.event. ActionListener; import javax.swing. JButton; import javax.swi

JLabel lbl3=new JLabel(); lbl3.setBounds (50, 400, 200, 25); //Creating btn for addition and setting its position x,y,width a//Creating btn for subtraction and setting its position x,y,width and height JButton btnSub=new JButton(Subtract); btnSub.sbtnMul.setBounds (270, 150, 100, 25); //In below statement we are binding the function call on click of button btnMul.addActi121 //In below statement we are binding the function call on click of button btnDiv.addActionListener(new ActionListener() {Сл NH л Сл л л // Adding all the control elements created above are adding into the JFrame add (lbl1); add (lbl2); add(txt1);

3. Please find below DLD_JFrame_Arithmetic.java file contents in text format for ready copying with proper comments to each of the line of the code:-

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

//Creating class DLD_JFrame_Arithmetic which is extending JFrame
public class DLD_JFrame_Arithmetic extends JFrame{

   //Constructor to initialize various control elements of frame
   public DLD_JFrame_Arithmetic() {

       //Creating lbl1 with message Enter first no and setting its position x,y,width and height
       JLabel lbl1=new JLabel("Enter first no:");
       lbl1.setBounds(50, 50, 100, 25);
      
       //Creating txt1 where user will enter first no as input and setting its position x,y,width and height
       JTextField txt1=new JTextField();
       txt1.setBounds(200, 50, 100, 25);

       //Creating lbl2 with message Enter second no and setting its position x,y,width and height
       JLabel lbl2=new JLabel("Enter second no:");
       lbl2.setBounds(50, 100, 100, 25);

       //Creating txt2 where user will enter second no as input and setting its position x,y,width and height
       JTextField txt2=new JTextField();
       txt2.setBounds(200, 100, 100, 25);

       //Creating lbl3 where we will get our final result and setting its position x,y,width and height
       JLabel lbl3=new JLabel();
       lbl3.setBounds(50, 400, 200, 25);

       //Creating btn for addition and setting its position x,y,width and height
       JButton btnAdd=new JButton("Add");
       btnAdd.setBounds(50, 150, 100, 25);
       //In below statement we are binding the function call on click of button
       btnAdd.addActionListener(new ActionListener() {

           @Override
           public void actionPerformed(ActionEvent e) {
               try {
                   //Getting number1 from the JTextField and parsing it into int type
                   int num1=Integer.parseInt(txt1.getText());
                  
                   //Getting number2 from the JTextField and parsing it into int type
                   int num2=Integer.parseInt(txt2.getText());
                  
                   //Performing addition of num1 and num2 and storing it into result of int type
                   int result=num1+num2;
                  
                   //Setting the result into the lbl3
                   lbl3.setText("Addition of "+num1+" and "+num2+" is "+result);
               } catch (Exception e1) {
                   //If any exception will occur then we will set the text Error inside lbl3
                   lbl3.setText("Error");
               }
           }
       });

       //Creating btn for subtraction and setting its position x,y,width and height
       JButton btnSub=new JButton("Subtract");
       btnSub.setBounds(160, 150, 100, 25);

       //In below statement we are binding the function call on click of button
       btnSub.addActionListener(new ActionListener() {

           @Override
           public void actionPerformed(ActionEvent e) {
               try {
                   //Getting number1 from the JTextField and parsing it into int type
                   int num1=Integer.parseInt(txt1.getText());
                  
                   //Getting number2 from the JTextField and parsing it into int type
                   int num2=Integer.parseInt(txt2.getText());
                  
                   //Performing subtraction of num1 and num2 and storing it into result of int type
                   int result=num1-num2;
                  
                   //Setting the result into the lbl3
                   lbl3.setText("Subtraction of "+num1+" and "+num2+" is "+result);
               } catch (Exception e1) {
                   //If any exception will occur then we will set the text Error inside lbl3
                   lbl3.setText("Error");
               }
           }
       });

       //Creating btn for multiplication and setting its position x,y,width and height
       JButton btnMul=new JButton("Multiply");
       btnMul.setBounds(270, 150, 100, 25);
      
      //In below statement we are binding the function call on click of button
       btnMul.addActionListener(new ActionListener() {

           @Override
           public void actionPerformed(ActionEvent e) {
               try {
                   //Getting number1 from the JTextField and parsing it into int type
                   int num1=Integer.parseInt(txt1.getText());
                  
                   //Getting number2 from the JTextField and parsing it into int type
                   int num2=Integer.parseInt(txt2.getText());
                  
                   //Performing multiplication of num1 and num2 and storing it into result of int type
                   int result=num1*num2;
                  
                   //Setting the result into the lbl3
                   lbl3.setText("Multiplication of "+num1+" and "+num2+" is "+result);
               } catch (Exception e1) {
                   //If any exception will occur then we will set the text Error inside lbl3
                   lbl3.setText("Error");
               }
           }
       });

       //Creating btn for division and setting its position x,y,width and height
       JButton btnDiv=new JButton("Divide");
       btnDiv.setBounds(380, 150, 100, 25);
      
      //In below statement we are binding the function call on click of button
       btnDiv.addActionListener(new ActionListener() {

           @Override
           public void actionPerformed(ActionEvent e) {
               try {
                   //Getting number1 from the JTextField and parsing it into int type
                   int num1=Integer.parseInt(txt1.getText());
                  
                   //Getting number2 from the JTextField and parsing it into int type
                   int num2=Integer.parseInt(txt2.getText());
                  
                   //If second number is 0 then the lbl3 text will be set as Error
                   if(num2==0)
                       lbl3.setText("Error");
                   else{
                   //Performing division of num1 and num2 and storing it into result of int type
                   int result=num1/num2;
                  
                   //Setting the result into the lbl3
                   lbl3.setText("Division of "+num1+" and "+num2+" is "+result);
                   }
               } catch (Exception e1) {
                  
                   //If any exception will occur then we will set the text Error inside lbl3
                   lbl3.setText("Error");
               }
           }
       });

      
       //Adding all the control elements created above are adding into the JFrame
       add(lbl1);
       add(lbl2);
       add(txt1);
       add(txt2);
       add(btnAdd);
       add(btnSub);
       add(btnMul);
       add(btnDiv);
       add(lbl3);

       //Setting the size of JFrame
       setSize(600, 600);

       //Exit the application on closing the window
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       //Displaying the JFrame
       setVisible(true);

   }
   public static void main(String[] args) {
      
       //Creating the object of DLD_JFrame_Arithmetic class
       DLD_JFrame_Arithmetic frame=new DLD_JFrame_Arithmetic();
   }
}

4. Please find below compilation screenshot of the above program as the above file is stored at D:/.

C. C:\Windows\system32\cmd.exe -java DLD_JFrame_Arithmetic D:\>javac DLD_JFrame_Arithmetic.java D:\>java DLD_JFrame_Arithmeti

5. Please find below various GUI output screenshots shown in JFrame of the above program for the inputs given:-

Enter first no: Enter second no: Add Subtract Multiply Divide Addition of 25 and 5 is 30

Enter first no: Enter second no: 5 Add Subtract Multiply Divide Subtraction of 25 and 5 is 20Enter first no: Enter second no: Enter second no: Add 5 Subtract Multiply Divide Multiplication of 25 and 5 is 125Enter first no: Enter second no: Enter second no: 5 Add S ubtract Multiply Divide Division of 25 and 5 is 5TO DI Enter first no: Enter second no: Enter second no: Add 0 Subtract Multiply Divide ΕΓΓΟΣ

6. Note:-

i) If you perform divide by 0 then an if statement is added to check the same and Error message will be printed inside the third label.

ii) If you keep blank any of the text field and will press any of the button then you will get the message Error.

iii) If you will enter any double value then also you will get the Error message. Since you have asked to take only integer and our code will fail while parsing double value.

iv) Important part of the code is marked in bold.

7. Though I put comments to each of the line of the code. Still if you have any query please feel free to reach me through comments section. I will be more than happy to help you further.

8. Please upvote if you like my answer.

Thanks!!

Happy Learning!!

Add a comment
Know the answer?
Add Answer to:
This Java program is giving me a good amount of trouble. Can someone solve this for...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Create a new class MathOP2 (MathOP2.java) that Inherits from MathOP You need to add multiply method...

    Create a new class MathOP2 (MathOP2.java) that Inherits from MathOP You need to add multiply method and divide method, both methods accepts two parameters and return a value. Create a test program with documentation to test all operators (at least 4) The TestMathOP should do the following      Enter the First number >> 5.5      Enter the Second Number >> 7.5      The sum of the numbers is 13      The subtract of the two numbers is -2.00      Do...

  • Can somebody help me with this assignment. I will highly appreciate. Also, please display the output...

    Can somebody help me with this assignment. I will highly appreciate. Also, please display the output as well. I need to use JAVA to to write the program. This is the sample output provided by my professor. HOME WORK: due 09.17.2019 (Rational Numbers) Create a class called Rational for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private instance variables of the class- the numerator and the denominator. Provide a constructor...

  • We are using blueJ for my java class, if you can help me id greatly appreciate...

    We are using blueJ for my java class, if you can help me id greatly appreciate it. Create a new Java class called AverageWeight. Create two arrays: an array to hold 3 different names and an array to hold their weights. Use Scanner to prompt for their name and weight and store in correct array. Compute and print the average of the weights entered using printf command. Use a loop to traverse and print the elements of each array or...

  • We use bluej for our JAVA class. If you can help me id greatly appreciate it....

    We use bluej for our JAVA class. If you can help me id greatly appreciate it. Create a new Java class called AverageWeight. Create two arrays: an array to hold 3 different names and an array to hold their weights. Use Scanner to prompt for their name and weight and store in correct array. Compute and print the average of the weights entered using printf command. Use a loop to traverse and print the elements of each array or use...

  • DIRECTIONS FOR THE WHOLE PROJECT BELOW BigInt class The purpose of the BigInt class is to...

    DIRECTIONS FOR THE WHOLE PROJECT BELOW BigInt class The purpose of the BigInt class is to solve the problem using short methods that work together to solve the operations of add, subtract multiply and divide.   A constructor can call a method called setSignAndRemoveItIfItIsThere(). It receives the string that was sent to the constructor and sets a boolean variable positive to true or false and then returns a string without the sign that can then be processed by the constructor to...

  • Java: In this assignment, you will create an accumulator accumulator-calculator that displays a sad face “...

    Java: In this assignment, you will create an accumulator accumulator-calculator that displays a sad face “ :-( “ whenever the number displayed by the calculator is negative and a happy face “ :-) ” whenever the number displayed is positive. The calculator responds to the following commands: num + , num - , num * , num / and C ( Clear ). After initial run, if the user clicks 8 and then presses the “+” button for example, the...

  • Rational Number *In Java* A rational number is one that can be expressed as the ratio...

    Rational Number *In Java* A rational number is one that can be expressed as the ratio of two integers, i.e., a number that can be expressed using a fraction whose numerator and denominator are integers. Examples of rational numbers are 1/2, 3/4 and 2/1. Rational numbers are thus no more than the fractions you've been familiar with since grade school. Rational numbers can be negated, inverted, added, subtracted, multiplied, and divided in the usual manner: The inverse, or reciprocal of...

  • This is java and make simple program. CPSC 1100. Thanks CSPS 1100 Lab 4 ay total...

    This is java and make simple program. CPSC 1100. Thanks CSPS 1100 Lab 4 ay total Also I would need a new name for the daubles. An example here might be double tRtalD-caradd xD, YD) 1. (a) We are going to begin with some simple math, reading input, and formatted output. Create a class called MuCalsustec Yau will not have an instance variable. Since you have no instance variables to initialize, you do nat need a constructar. Do NOT create...

  • python: def functionSolver(function: callable)->str You will be given a function as a parameter, the function you...

    python: def functionSolver(function: callable)->str You will be given a function as a parameter, the function you are given only accepts two number parameters and produces a float value. It is your job to figure out what mathematical operation the function you are given is performing by passing it many different parameters. The possible operations the function can perform are: add, subtract, multiply, and divide. The given function will only perform a single operation, it will not change after consecutive invocations....

  • Program using visual basic.net You will create a very simple two numbers calculator with save options;...

    Program using visual basic.net You will create a very simple two numbers calculator with save options; here is the specifications for the application. Create a form divided vertically in two halves with right and left panels 1- In the left panel you will create the following control, the label or the value of the control will be in "" and the type of the control will in [] a- "First Number" [textbox] b- "Second number" [texbox] c- "Result" [textbox] -...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT