I have to write an applet that asks the user to enter two floating-point numbers, obtains the two numbers from the user and draws their sum, product, difference and quotient. This is what I have so far. Can anyone make sure I am on the right track.

import java.awt.Graphics;       // program uses class Graphics
import javax.swing.JApplet;     // program uses class JApplet
import javax.swing.JOptionPane; // program uses class JOptionPane

public class AdditionApplet extends JApplet
   private double sum; // sum of values entered by user

   // initialize applet by obtaining values from user
   public void init()
      String firstNumber;  // first string entered by user
      String secondNumber; // second string entered by user

      double number1; // first number to add
      double number2; // second number to add

      // obtain first number from user
      firstNumber = JOptionPane.showInputDialog(
         "Enter first floating-point value" );

      // obtain second number from user
      secondNumber = JOptionPane.showInputDialog(
         "Enter second floating-point value" );

      // convert numbers from type String to type double
      number1 = Double.parseDouble( firstNumber );
      number2 = Double.parseDouble( secondNumber );

      sum = number1 + number2; // add numbers
      product = number1 * number2; // multiply numbers
      difference = number1 - number2; // subtract numbers
      quotient = number1 / number2; // divide numbers

   } // end method init

   // draw results in a rectangle on applet’s background
   public void paint( Graphics g )
      super.paint( g ); // call superclass version of method paint

      // draw rectangle starting from (15, 10) that is 270
      // pixels wide and 20 pixels tall
      g.drawRect( 15, 10, 270, 20 );

      // draw results as a String at (25, 25)
      g.drawString( "The sum is " + sum, 25, 25 );
   } // end method paint
} // end class AdditionApplet 

Edited by Reverend Jim: Fixed formatting

8 Years
Discussion Span
Last Post by darkagn

Hi Ryano24,

That all looks pretty good to me. I guess your next step is to add some drawString methods to display the difference, product and quotient. The only comment I have is what happens if the second number entered by the user is 0? Or if either string entered is not a number? You can't just blindly trust that users will enter what you tell them to. Other than that your code seems ok at a quick glance :)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.