Question

In: Computer Science

This project involves writing a program to calculate the terms of the following sequence of numbers:...

This project involves writing a program to calculate the terms of the following sequence of numbers: 0 1 1 3 5 11 21 43 … where each term is twice the second previous term plus the previous term. The 0th term of the sequence is 0 and the 1st term of the sequence is 1.
The example below shows how to calculate the next sequence term:
Current sequence: 0 1 Calculate next term: 2 * 0 + 1 = 1
Current sequence: 0 1 1 Calculate next term: 2 * 1 + 1 = 3
Current sequence: 0 1 1 3 Calculate next term: 2 * 1 + 3 = 5
Current sequence: 0 1 1 3 5 Calculate next term: 2 * 3 + 5 = 11
… etc.

The pair of radio buttons allows the user to choose whether an iterative or recursive method is used to compute the term of the sequence (the Iterative radio button should be initially selected). When the user enters a value for n and then clicks the Compute button, the nth term of the sequence (counting from zero) should be displayed in the Result field. The Efficiency field should contain the number of calls to the recursive method when the recursive option is chosen and the number of iterations of the loop when the iterative option is selected. The program will check the validity of the user input value which should be a positive integer. A message will be shown in a JOptionPane for illegal entered values.
When the window is closed, the efficiency values should be computed with values of n from 0 to 20 and written to a text file outData.txt. Each line of the file should contain the value of n, the efficiency of the recursive method for that value of n and the efficiency of the iterative method. The values should be separated by commas so the file can be opened with Excel and used to graph the value of the efficiencies for both the recursive and iterative options along the y axis and with the value of n along the x-axis. The graph should be included in the solution description document that accompanies this project and should also contain a brief explanation of the observed results.
The program should consist of two classes: P3GUI and Sequence.
1. Class P3GUI should define the Swing based GUI and should be hand-coded and not generated by a GUI generator. In addition to the main method and a constructor to build the GUI, an event handler will be needed to handle the Compute button click and another handler will be needed to produce the file described above when the window is closed. The latter handler should be an object of an inner class that extends the WindowAdapter class.
2. Class Sequence should be a utility class meaning that all its methods must be class (static) methods and no
objects should be able to be generated for that class. It should contain three public methods:
a. The first method computeIterative should accept a value of n and return the corresponding element in
the sequence using iteration.
b. The second method computeRecursive should accept a value of n and return the corresponding element
in the sequence using recursion. This method will initialize the efficiency counter before calling the private
recursive method that will actually perform the recursive computation.
c. The third method getEfficiency will return the efficiency counter left behind by the previous call to either
of the above two methods.

Solutions

Expert Solution

P3GUI.java
------------------------------------------------------------
import java.awt.*;
import java.awt.event.*;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

public class P3GUI extends javax.swing.JDialog implements ActionListener{
    //instance variables
    private final JFrame frame;
    private JPanel panel;
    private final JRadioButton recursiveButton;
    private final JRadioButton iterativeButton;
    private final JButton computeButton;
    private final JTextField nTextField;
    private final JTextField resultTextField;
    private final JTextField efficiencyTextField;
    private static Sequence sequence;

    /**
     *
     * Constructor to create GUI
     */
    public P3GUI(){

        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setTitle("Project 3");
        frame.setSize(300,200);
        frame.setLocationRelativeTo(null);
        recursiveButton = new JRadioButton("Recursive");
        iterativeButton = new JRadioButton("Iterative");
        computeButton = new JButton("Compute");
        nTextField = new JTextField();
        resultTextField = new JTextField();
        efficiencyTextField = new JTextField();

        ButtonGroup group = new ButtonGroup();
        group.add(recursiveButton);
        group.add(iterativeButton);
        iterativeButton.setSelected(true);

        iterativeButton.setActionCommand("iterative");
        recursiveButton.setActionCommand("recursive");
        computeButton.setActionCommand("compute");
        iterativeButton.addActionListener(P3GUI.this);
        recursiveButton.addActionListener(P3GUI.this);
        computeButton.addActionListener(P3GUI.this);

        frame.setLayout(new GridLayout(6,2,3,3));

        frame.add(new JLabel(""));
        frame.add(iterativeButton);
        frame.add(new JLabel(""));
        frame.add(recursiveButton);
        frame.add(new JLabel("Enter n: (1-25)"));
        frame.add(nTextField);
        frame.add(new JLabel(""));
        frame.add(computeButton);
        frame.add(new JLabel("Result:"));
        frame.add(resultTextField);
        frame.add(new JLabel("Efficiency:"));
        frame.add(efficiencyTextField);
        frame.addWindowListener(new WindowAdapterImpl());

        frame.setVisible(true);
    }

    public boolean isNumeric(String str){
        try
        {
            double d = Double.parseDouble(str);
        }
        catch(NumberFormatException nfe)
        {
            JOptionPane.showMessageDialog(frame, "Please Enter a Valid Numerical Value");
            nTextField.setText("");
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        // TODO code application logic here
        P3GUI foo = new P3GUI();

    }

    /**
     * Controls the action performed when a button is clicked

     */
    @Override
    public void actionPerformed(ActionEvent e) {
        String event = e.getActionCommand();
        String text;
        String result;

        switch (event){

            case "compute":

                text = nTextField.getText();
                if(isNumeric(text) == false) break;

                if(iterativeButton.isSelected()){
                    result = ""+Sequence.computeIterative(Integer.parseInt(text));
                }
                else if(recursiveButton.isSelected()){
                    result = ""+Sequence.computeRecursive(Integer.parseInt(text));
                }
                else{
                    result = "";
                }
                resultTextField.setText(result);
                efficiencyTextField.setText(""+Sequence.getEfficiency());
                break;
        }
    }

    /**
     * Class that defines a windowAdapter to override windowClosing method to perform function on window close
     */
    private static class WindowAdapterImpl extends WindowAdapter {

        public WindowAdapterImpl() {
        }

        @Override
        public void windowClosing(WindowEvent e){
            try {
                int iterativeE;
                int recursiveE;
                FileWriter fw = new FileWriter("Efficiency Values.csv");
                for(int n = 0; n <= 10; n++){
                    Sequence.computeIterative(n);
                    iterativeE = Sequence.getEfficiency();
                    Sequence.computeRecursive(n);
                    recursiveE = Sequence.getEfficiency();
                    fw.write(n+","+iterativeE+","+recursiveE+"\n");
                }
                fw.close();
            } catch (IOException ex) {
                Logger.getLogger(P3GUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }


}
-------------------------------------------------------------------------------------------
Sequence.java
-------------------------------------------------
public class Sequence {

    private static int efficiency;

    /**Constructor to initialize instance variable
     */
    public Sequence(){
        efficiency = 0;
    }

    /**Computes nth term iteratively, where the nth term is 2 times the previous number plus the next previous number
     */
    public static int computeIterative(int n){

        efficiency = 0;
        int[] s = new int[n+1];

        for(int i = 0; i <= n; i++){
            if(i==0){
                s[i]=0;
            }
            else if(i==1){
                s[i]=1;
            }
            else{
                s[i] = (s[i-1]*2 + s[i-2]);
            }

            efficiency++;
        }

        return s[n];

    }

    /**Helper method for recursive() method
     */
    public static int computeRecursive(int n){
        efficiency = 0;
        return recursive(n);


    }

    /**Computes nth term recursively, where the nth term is 2 times the previous number plus the next previous number
     */
    private static int recursive(int n){
        efficiency++;
        if(n <= 1){
            return n;
        }

        return recursive(n-1)*2+recursive(n-2);

    }

    /**
     * Returns the value of the efficiency counter
     */
    public static int getEfficiency(){
        return efficiency;
    }

}


Related Solutions

(a) The Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence,...
(a) The Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and are characterised by the fact that every number after the first two is the sum of the two preceding ones: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 114, … etc. By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two. We define Fib(0)=0,...
A management device that involves mapping out a sequence of programs or project steps is a....
A management device that involves mapping out a sequence of programs or project steps is a. performance evaluation review technique. b. management by objectives. c. critical path method. d. strategic analysis.
The sixth assignment involves writing a Python program to read in the temperatures for ten consecutive...
The sixth assignment involves writing a Python program to read in the temperatures for ten consecutive days in Celsius and store them into an array. The entire array should then be displayed. Next each temperature in the array should be converted to Fahrenheit and the entire array should be again be displayed. The formula for converting Celsius to Fahrenheit is °F = (°C × 1.8) + 32. Finally, the number of cool, warm and hot days should be counted and...
This involves writing a Python program to determine the body-mass index of a collection of six...
This involves writing a Python program to determine the body-mass index of a collection of six individuals. Your program should include a list of six names. Using a for loop, it should successively prompt the user for the height in inches and weight in pounds of each individual. Each prompt should include the name of the individual whose height and weight is to be input. It should call a function that accepts the height and weight as parameters and returns...
The second assignment involves writing a Python program to compute the price of a theater ticket....
The second assignment involves writing a Python program to compute the price of a theater ticket. Your program should prompt the user for the patron's age and whether the movie is 3D. Children and seniors should receive a discounted price. There should be a surcharge for movies that are 3D. You should decide on the age cutoffs for children and seniors and the prices for the three different age groups. You should also decide on the amount of the surcharge...
Your final project will satisfy the following scenario: You are writing a program that will act...
Your final project will satisfy the following scenario: You are writing a program that will act as an ATM machine by the end of this course. In order to access the ATM, the customer must enter their user name and their passcode. After 3 incorrect attempts at entering the user name and password, the program will end. The list of legitimate users along with their user ID, passcode, and account balance will be provided to you. There are only 5...
Write a test program that prompts the user to enter a sequence of numbers ending with...
Write a test program that prompts the user to enter a sequence of numbers ending with 0, and invokes this method to return the largest number in the input. Use inheritance and polymorphism approach. in java please
1a) If I'm writing a program which involves many insertion and deletion operations, and memory is...
1a) If I'm writing a program which involves many insertion and deletion operations, and memory is not a concern, which of the following should I choose to hold my data? A: linked list B: fixed-size array C: dynamic array D: any of the above 1b) What about if I'm writing a program and I want the program to be flexible on the data with various sizes, and the program also needs to provide fast access to the data? Which of...
Both TCP and RTP use sequence numbers. Investigate whether or not the sequence numbers in the...
Both TCP and RTP use sequence numbers. Investigate whether or not the sequence numbers in the TCP and RTP protocols play the same role.
For the following exercises, write the first eight terms of the sequence.
For the following exercises, write the first eight terms of the sequence.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT