In: Computer Science
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.
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;
}
}