March 2018

Saturday, 31 March 2018

Hypotenuse of a right triangle


Write an applet that reads in values for side1 and side2 from a JTextField object and performs the calculations with the hypotenuse method.

Note: Define a method hypotenuse that calculates the length of the hypotenuse of a right triangle when the lengths of the other two sides are given. The method should take two arguments of type double and return the hypotenuse as a double.

The Program

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Hypotenus extends JApplet implements ActionListener {
 JLabel side1Label, side2Label, resultLabel;
 JTextField side1Field, side2Field, resultField;

 //create GUI Components
 public void init()
 {
  Container container = getContentPane();
  container.setLayout(new FlowLayout());
 
  side1Label = new JLabel("Enter side1:");
  side1Field = new JTextField(10);
  container.add(side1Label);
  container.add(side1Field);
 
  side2Label = new JLabel("Enter side2:");
  side2Field = new JTextField(10);
  container.add(side2Label);
  container.add(side2Field);
 
  side2Field.addActionListener(this);
 
  resultLabel = new JLabel ("Hypotenus is: ");
  resultField = new JTextField(15);
  resultField.setEditable(false);
  container.add(resultLabel);
  container.add(resultField);
 
 }

 public void actionPerformed (ActionEvent event)
 {
  double side1, side2, hypo = 0;
 
  side1 = Double.parseDouble(side1Field.getText());
  side2 = Double.parseDouble(side2Field.getText());
 
  showStatus("Calculating.........");
 
  hypo = hypotenus(side1, side2); //hypo calls method hypotenus to calculate and return result;
 
  showStatus("Done!");
  resultField.setText(Double.toString(hypo) );
 }

 public double hypotenus(double x, double y)
 {
  double result = Math.sqrt((x*x) + (y*y));
 
  return result;
 }

}

Maximum of Decimal Numbers


Write an applet that allows user to input three decimal numbers and it determines and return the largest of them.

The program
//Finding the maximum of three floating point numbers

import java.awt.Container;

import javax.swing.*;

public class MaximumTest extends JApplet{
 
  public void init()
  {
    //allows the user to obtain input as a string.

    String s1 = JOptionPane.showInputDialog("Enter first floating-point value");
    String s2 = JOptionPane.showInputDialog("Enter second floating-point value");
    String s3 = JOptionPane.showInputDialog("Enter third floating-point value");
   
    //method Double.parseDouble is used to convert the strings input by the user to double values
    double number1 = Double.parseDouble( s1 );
    double number2 = Double.parseDouble( s2 );
    double number3 = Double.parseDouble( s3 );
   
    //method maximum return returns the result to init, using a return statement
    //this program assigns the result to variable max
    double max = maximum(number1, number2, number3);
   
    //create JTextArea to display results
    JTextArea outputArea = new JTextArea();
   
    //display numbers and maximum value
    outputArea.setText("number1: " + number1 + "\nnumber2: " + number2 + "\nnumber3: " + number3 + "\nMaximum is: " + max );
   
    //get applet's GUI component to display area
    Container container = getContentPane();
   
    //attach outputArea to container
    container.add(outputArea);
  }
 
  public double maximum(double x, double y, double z )
  {
    return Math.max(x, Math.max(y, z));
  }
}

The Fibbonacci Series


Write a program in an applet that enables a user to input an integer in a textfield and the applets indicates the ith Fibonacci number to calculate.

The Fibonacci series begins with 0 and 1 and has the property that each subsequent Fibonacci number is the sum of the previous two Fibonacci numbers.

The Fibonacci series may be defined recursively as follows:
fibonacci(0) = 0
fibonacci(1) = 1

fibonacci(n) = fibonacci(n-1) + fibonacci (n-2)

The Program

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class FibonacciTest extends JApplet implements ActionListener {
 JLabel numberLabel, resultLabel;                     //initialize variable for the gui
 JTextField numberField, resultField;

 //set up gui (Graphics User Interface)
 public void init()
 {
  Container container = getContentPane();
  container.setLayout(new FlowLayout());

  //create numberLabel and attach it to the content pane
  numberLabel = new JLabel ("Enter an integer and press Enter");
  container.add(numberLabel);

  //create numberField and attach it to the content pane
  numberField = new JTextField(10);
  container.add(numberField);

  //register this applet as numberField's ActionListener
  numberField.addActionListener(this);

  //create resultLabel and attach it to the content pane
  resultLabel = new JLabel("Fibonacci Value is");
  container.add(resultLabel);

  //create resultField and attach it to the content pane
  resultField = new JTextField(15);
  resultField.setEditable(false);
  container.add(resultField);

 }

 //obtain user input and call method fibonacci
 public void actionPerformed (ActionEvent event)
 {
   //Fibonacci numbers tend to become large quickly, therefore, we use long as the parameter type and return type of the Fibonacci.

  long number, fibonacciValue;

  //obtain user's input and convert to long
  number = Long.parseLong(numberField.getText() );

  showStatus("Calculating.........");

  //Calculate fibonacci value for number input
  fibonacciValue = fibonacci(number); //method fibonacci is called here

  //indicate processing complete and display result
  showStatus("Done!");
  resultField.setText(Long.toString(fibonacciValue) );
 }


 public long fibonacci(long n) //Note n is the number chosen to represent number in method fibonacci(number);
 { //Note all method that has the arguments long, int, double, float must return its answer to the called method.
  //base case
  if(n== 0 || n == 1)
   return n;

  //recursive step
  else
   return fibonacci(n-1) + fibonacci(n-2);


 }

}

Friday, 30 March 2018

Sum, Product, Difference, & Quotient of two Integers Using an Applet Application


Write an application that asks the user to enter two numbers, obtains the numbers from the user and prints the sum, product, difference and quotient(division) of the numbers.

//import java packages
import java.awt.Graphics;
import javax.swing.*;

public class ArithmeticApplet extends JApplet {

 double sum;                // sum of values entered by user
 double product;          //product of values entered by user
 double difference;     //difference of values entered by user
 double quotient;      //division 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/multiply/subtract/divide
  double number2;            //second number to add/multiply/subtract/divide
 
  //obtain string from user
  firstNumber = JOptionPane.showInputDialog("Enter first floating number");
  secondNumber = JOptionPane.showInputDialog("Enter second floating number");
 
  //convert from type string to type double
  number1= Double.parseDouble(firstNumber);
  number2= Double.parseDouble(secondNumber);
 
  //compute numbers
  sum = number1 + number2;
  product= number1 * number2;
  difference = number1 - number2;
  quotient = number1 / number2;
 
 }
 //draw results in a rectangle on applet's background
 public void paint (Graphics g)
 {
  //call superclass version of method paint
  super.paint(g);
 
  //draw rectangle starting from (15,10) at (270 pixels wide, 80 pixels tall
  g.drawRect(15, 10, 270, 80);
 
  //draw results as a String at (25,25)
  g.drawString("The sum is: " + sum,25, 25);
  g.drawString("The product is: "+product, 25,40);
  g.drawString("The difference is: " + difference, 25, 55);
  g.drawString("The quotient is: " + quotient, 25, 70);

 }

}

Coordinates of Two Points using an Applet


Question: Write an applet that enables a user to calculate the distance between two points (x1,y1) and (x2, y2) All numbers and return values should be of type double and the result should give the coordinates of the points.

This is an applet that calculates the distance between two points using method distance to find the two points.

The Program
//import declarations.
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Coordinates extends JApplet implements ActionListener {

 JLabel x1Label,x2Label,y1Label, y2Label, resultLabel; //initialize variable for the gui
 JTextField x1Field, x2Field, y1Field, y2Field, resultField;
 JButton getButton;


 //set up GUI components
 public void init()
 {
  Container container = getContentPane();
  container.setLayout(new FlowLayout());
 
  //create numberLabel and attach it to the content pane
  x1Label = new JLabel ("Enter x1 Cordinate");
  container.add(x1Label);
  //create numberField and attach it to the content pane
  x1Field = new JTextField(10);
  container.add(x1Field);
 

  //create numberLabel and attach it to the content pane
  y1Label = new JLabel ("Enter y1 Cordinate");
  container.add(y1Label);
  //create numberField and attach it to the content pane
  y1Field = new JTextField(10);
  container.add(y1Field);
 

  //create numberLabel and attach it to the content pane
  x2Label = new JLabel ("Enter x2 Cordinate");
  container.add(x2Label);
  //create numberField and attach it to the content pane
  x2Field = new JTextField(10);
  container.add(x2Field);

  //create numberLabel and attach it to the content pane
  y2Label = new JLabel ("Enter y2 Cordinate");
  container.add(y2Label);
  //create numberField and attach it to the content pane
  y2Field = new JTextField(10);
  container.add(y2Field);
 
  //create button user clicks to add number
  getButton = new JButton("Get Distance");
  container.add(getButton);
   
  //register this applet as addButton ActionListener
  getButton.addActionListener(this);
 
  //create resultLabel and attach it to the content pane
  resultLabel = new JLabel("Distance is");
  container.add(resultLabel);
 
  //create resultField and attach it to the content pane
  resultField = new JTextField(15);
  resultField.setEditable(false);
  container.add(resultField);
 
 }

 public void actionPerformed (ActionEvent event )

 {
  double DistanceValue = 0; double x1, x2, y1, y2;
 
  //obtain user's input and convert to long
  x1 = Double.parseDouble(x1Field.getText() );
  x2 = Double.parseDouble(x2Field.getText() );
  y1 = Double.parseDouble(y1Field.getText() );
  y2 = Double.parseDouble(y2Field.getText() );
 
  showStatus("Calculating.........");
 
  //Calculate DistanceValue for number input
  DistanceValue = distance(x1,x2,y1,y2); //method distance is called here to calculate the distance
            //btweeen the two point and return result
 
  //indicate processing complete and display result
  showStatus("Done!");
  resultField.setText(Double.toString(DistanceValue) );
 }

 public double distance (double a, double b, double c, double d) //method distance
 {
  return Math.sqrt( ((d+b)*(d+b)) + ((c+a)*(c+a)) );
 }
}

Adding Integers in a Command Window


Write an application that asks the user to enter two integers, obtains the numbers from the user and displays the sum of the two integers in a command window.
This program adds two integers using scanner a java class as input
(//) is used as a comment to explain the program more clearly

import java.util.Scanner;            // this imports  class Scanner in java.utility

//A Scanner enables a program to read data. data which are numbers and strings for use in a program
//Note: Always leave white line spaces in between your programs to be more readable and clear.

public class AddingIntegersUsingScanner {

//the public class begins a class declaration for class AddingIntegersUsingScanner. Every program in java consists of at least
//one class declaration that is defined by you the programmer.

public static void main (String [] args) // the starting point of every java applications
{
//create a scanner to obtain input from the command prompt
Scanner input = new Scanner(System.in);

int number1; // first number to add
int number2; //second number to add
int sum;  // sum of number number 1 and number 2

System.out.print("Enter first integer: "); // prompts user to input first integer
number1 = input.nextInt(); // reads in integer from the user

System.out.print("Enter second integer: ");   // prompts user to input second integer
number2 = input.nextInt(); // prompts user to input second integer

sum = number1 + number2; //adds the integers

System.out.printf("Sum is %d\n", sum)           //displays the results
}

}