Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Problem, JAVA: I need help computing the values of \'n\' from 0 to 10 and writin

ID: 3572219 • Letter: P

Question

Problem, JAVA: I need help computing the values of 'n' from 0 to 10 and writing them to a text file, along with iterative efficiency and recursive efficiency. Each of the three outputs should be on the same line and should have a comma separating each one value on the line, starting a new line after each new value of 'n'. Any help is always welcome. The code and the assignment instructions are included.

GUI.java

package project3;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class GUI extends JFrame{
    private final Font font = new Font ("Arial", Font.BOLD, 18);
    private final JFrame frame = new JFrame();

    private final ButtonGroup userSelection = new ButtonGroup();
    private final JLabel enterLabel = new JLabel("Enter a number: ");
    private final JLabel resultLabel = new JLabel("Result");
    private final JLabel effLabel = new JLabel("Efficiency");

    private final JRadioButton iterativeBtn = new JRadioButton("Iterative");
    private final JRadioButton recursiveBtn = new JRadioButton("Recursive");

    private final JTextField enterField = new JTextField(15);
    private final JTextField resultField = new JTextField();
    private final JTextField effField = new JTextField();

    private final JButton calcBtn = new JButton("Compute");

    private final JPanel choicePanel = new JPanel();
    private final JPanel enterPanel = new JPanel();
    private final JPanel buttonPanel = new JPanel();
    private final JPanel resultPanel = new JPanel();
    private final JPanel mainPanel = new JPanel();

    private final String fileName = "output.txt";
    private PrintWriter output;
    private FileWriter fw;
    private BufferedWriter bw;

    /*
    * Constructor for the MyGui View
    */
    public GUI(){
        setFrame();
        setPanels();
        setAttributes();
        addWindowListener(new CloseApp());
    }


    /*
    * Sets the attributes for the frame
    */
    private void setFrame() {
    
        setSize(600, 300);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Recursive vs Iterative");
        add(mainPanel);
    }

    /*
    * Sets the attributes for the components
    */
    private void setAttributes(){
        mainPanel.setLayout(new GridLayout(4,1));
        resultPanel.setLayout(new GridLayout(2,2));
        userSelection.add(iterativeBtn);
        userSelection.add(recursiveBtn);
        iterativeBtn.setFont(font);
        recursiveBtn.setFont(font);
        enterLabel.setFont(font);
        resultLabel.setFont(font);
        effLabel.setFont(font);
        calcBtn.setFont(font);
        resultField.setEditable(false);
        effField.setEditable(false);
        iterativeBtn.setSelected(true);
        calcBtn.addActionListener(new buttonClick());
    }

    /*
    * Adds the components to the Panels
    * Adds the panels to the mainPanel
    */
    public void setPanels(){
        choicePanel.add(iterativeBtn);
        choicePanel.add(recursiveBtn);
    
        enterPanel.add(enterLabel);
        enterPanel.add(enterField);
    
        buttonPanel.add(calcBtn);
    
        resultPanel.add(resultLabel);
        resultPanel.add(resultField);   
        resultPanel.add(effLabel);
        resultPanel.add(effField);
    
        mainPanel.add(choicePanel);
        mainPanel.add(enterPanel);
        mainPanel.add(buttonPanel);
        mainPanel.add(resultPanel);
    }

    /*
    * Method that calls the Sequence class and passes in the integer
    */
    private void callSequence(int a){
        if(iterativeBtn.isSelected()){
            int iterativeValue = Sequence.computeIterative(a);
            long itEff = (Sequence.counter + 1);
            resultField.setText(Integer.toString(iterativeValue));
            effField.setText(Long.toString(itEff));
            //Print to file
            iPrintToFile(a, itEff);
       
            Sequence.resetCounter(0);
        }
    
        else if (recursiveBtn.isSelected()){
            int recursiveValue = Sequence.computeRecursive(a);
            long recEff = Sequence.counter;
            resultField.setText(Integer.toString(recursiveValue));
            effField.setText(Long.toString(recEff));
            //Print the values to the file.
            rPrintToFile(a, recEff);
        
            Sequence.resetCounter(0);
        }
    }

    /*
    * Test method that parses the text to an Integer and ensures it's not negative.
    */
    private int testMethod(String enterText){
        int a = 0;
        int b = 0;
        try{
            a = Integer.parseInt(enterText);
        }
        catch(NumberFormatException e){
            JOptionPane.showMessageDialog(frame, "Please enter a whole number.");
        }
    
        if (a >= 0){
            b = a;
        }
        else {
            JOptionPane.showMessageDialog(frame, "Please enter a positive whole number.");
        }
    
        return b;
    }

    /*
    * Print method that takes in the values and prints them to a file
    */
    private void iPrintToFile(int sequenceValue, long effValue){
        output.println(sequenceValue + "," + effValue);
        output.close();
    }

    private void rPrintToFile(int sequenceValue, long effValue){
        output.println(sequenceValue + "," + "," + effValue);
        output.close();
    }


    /**
     *Inner class that handles the Compute Button
     * Opens the filewriter, the bufferedwriter and the printwriter
     */
    private class buttonClick implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            int retrievedValue = testMethod(enterField.getText());
            try{
                fw = new FileWriter(fileName, true);
                bw = new BufferedWriter(fw);
                output = new PrintWriter(bw);
            }
            catch(IOException g){
                JOptionPane.showMessageDialog(frame, "File was not found.");
            }

            callSequence(retrievedValue);
        }
    
    }

    /**
     *Inner class that handles the WindowClose Event
     * Closes the filewriter and the bufferedwriter
     */
    private class CloseApp extends WindowAdapter{
        public void windowClosing(WindowEvent e)
        {
            try{
                fw.close();
                bw.close();
            }
            catch(IOException f){}
        }
    
        public void windowClosed(WindowEvent e){
            System.exit(0);
        }
    }
}  

Sequence.java

package project3;

public final class Sequence {

        public static int counter;
  
        private Sequence(){
            counter = 0;
        }
  
        /**
         *Computes the sequence values iteratively
         */
        public static int computeIterative(int n){
            int previous = 0;
            int current = 1;
        
            if(n==0){
                return previous;
            }
        
            for(int i = 1; i < n; i++){
                int result = (2 * current) + previous;
                previous = current;
                current = result;
                getEfficiency();
                int effI = counter;
            }

            return current;
        }
  
        /**
         *Computes the sequence values recursively
         */
        public static int computeRecursive(int n){
            if(n == 0){
                int result = 0;
                getEfficiency();
                return result;
            }
        
            if(n == 1){
                int result = 1;
                getEfficiency();
                return result;
            }

            int num1 = computeRecursive(n-1);
            int num2 = computeRecursive(n-2);
            int newTerm = ((2 * num1) + num2);
            getEfficiency();
            int effR = counter;
            return newTerm;
        }
  
        /**
         *Calculates the efficiency for each method
         */
        public static void getEfficiency(){
            counter++;
        }
  
        /*
        * Resets the counter variable
        */
        public static void resetCounter(int a){
            counter = a;
        }
  
   }// End Sequence.java

nstructions The third programming project involves writing a program to calculate the terms of the following sequence of numbers: 0 1 2 5 12 29 where each term of the is twice the previous term plus the second previous term. The 0th term of the sequence is 0 and the 1st term of the sequence is 1.The interface to the program sequence should be a GUI that looks similar to the following Project 3 X O Iterative Recursive nter n Compute sult 29 fficiency: 15 The pair of radio buttons a the user to choose whether an iterative or recursive method is used to compute the term of the sequence. When the user enters a value for n and then clicks the Compute button, the th term of the sequence should be displayed in the n d should contain the number of calls to Result field. The ciency the recursive method when the recursive option is chosen and the number of iterations of the loop when the iterative option is selected. The Iterative radio button should be initially set to selected en the window is closed, the efficiency values should be comp with values of n from 0 to 10 and written to a file. Each line of the file should contain the value of n, the efficiency of the iterative method for that value of n and the efficiency of the recursive 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 iterative and recursive options along the y axis with the value of n along the X-axis. The graph should be included as your test plan in the Word document that accompanies this project and should also contain a brief explanation of the observed results The program should consist of two classes. The first class should define the GUI and should be hand 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 The other class should be named Sequence. It 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 The first method computeIterative should accept a value of n and return the corresponds element in the sequence using iteration The second method computeRecursive should accept a value of n and return the corresponds element in the sequence using recursion. This method with be a helper method because it will need to initialize the efficiency counte r before calling the private recursive method that will actually perform the recursive computation The third method getEfficiency will return the efficiency counter left behind by the previous call to either of the above two methods

Explanation / Answer

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class GUI extends JFrame
{
private final Font font = new Font ("Arial", Font.BOLD, 18);
private final JFrame frame = new JFrame();

private final ButtonGroup userSelection = new ButtonGroup();
private final JLabel enterLabel = new JLabel("Enter a number: ");
private final JLabel resultLabel = new JLabel("Result");
private final JLabel effLabel = new JLabel("Efficiency");

private final JRadioButton iterativeBtn = new JRadioButton("Iterative");
private final JRadioButton recursiveBtn = new JRadioButton("Recursive");

private final JTextField enterField = new JTextField(15);
private final JTextField resultField = new JTextField();
private final JTextField effField = new JTextField();

private final JButton calcBtn = new JButton("Compute");

private final JPanel choicePanel = new JPanel();
private final JPanel enterPanel = new JPanel();
private final JPanel buttonPanel = new JPanel();
private final JPanel resultPanel = new JPanel();
private final JPanel mainPanel = new JPanel();

private final String fileName = "output.txt";
private PrintWriter output;
private FileWriter fw;
private BufferedWriter bw;
/*
* Constructor for the MyGui View
*/
public GUI()
{
setFrame();
setPanels();
setAttributes();
addWindowListener(new CloseApp());
}

/*
* Sets the attributes for the frame
*/
public void setFrame() {
  
setSize(600, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Recursive vs Iterative");
add(mainPanel);
}

/*
* Sets the attributes for the components
*/
public void setAttributes(){
mainPanel.setLayout(new GridLayout(4,1));
resultPanel.setLayout(new GridLayout(2,2));
userSelection.add(iterativeBtn);
userSelection.add(recursiveBtn);
iterativeBtn.setFont(font);
recursiveBtn.setFont(font);
enterLabel.setFont(font);
resultLabel.setFont(font);
effLabel.setFont(font);
calcBtn.setFont(font);
resultField.setEditable(false);
effField.setEditable(false);
iterativeBtn.setSelected(true);
calcBtn.addActionListener(new buttonClick());
}

/*
* Adds the components to the Panels
* Adds the panels to the mainPanel
*/
public void setPanels(){
choicePanel.add(iterativeBtn);
choicePanel.add(recursiveBtn);
  
enterPanel.add(enterLabel);
enterPanel.add(enterField);
  
buttonPanel.add(calcBtn);
  
resultPanel.add(resultLabel);
resultPanel.add(resultField);   
resultPanel.add(effLabel);
resultPanel.add(effField);
  
mainPanel.add(choicePanel);
mainPanel.add(enterPanel);
mainPanel.add(buttonPanel);
mainPanel.add(resultPanel);
}

/*
* Method that calls the Sequence class and passes in the integer
*/
public void callSequence(int a){
if(iterativeBtn.isSelected()){
int iterativeValue = Sequence.computeIterative(a);
long itEff = (Sequence.counter + 1);
resultField.setText(Integer.toString(iterativeValue));
effField.setText(Long.toString(itEff));
//Print to file
iPrintToFile(a,iterativeValue,itEff);

Sequence.resetCounter(0);
}
  
else if (recursiveBtn.isSelected()){
int recursiveValue = Sequence.computeRecursive(a);
long recEff = Sequence.counter;
resultField.setText(Integer.toString(recursiveValue));
effField.setText(Long.toString(recEff));
//Print the values to the file.
rPrintToFile(a,recursiveValue, recEff);
  
Sequence.resetCounter(0);
}
}

/*
* Test method that parses the text to an Integer and ensures it's not negative.
*/
public int testMethod(String enterText){
int a = 0;
int b = 0;
try{
a = Integer.parseInt(enterText);
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(frame, "Please enter a whole number.");
}
  
if (a >= 0){
b = a;
}
else {
JOptionPane.showMessageDialog(frame, "Please enter a positive whole number.");
}
  
return b;
}

/*
* Print method that takes in the values and prints them to a file
*/
public void iPrintToFile(int sequenceValue,int iterativeValue, long effValue){
output.println(sequenceValue + ","+iterativeValue+"," + effValue);
output.close();
}

public void rPrintToFile(int sequenceValue,int recursiveValue, long effValue){
output.println(sequenceValue + "," +recursiveValue+","+ effValue);
output.close();
}

/**
*Inner class that handles the Compute Button
* Opens the filewriter, the bufferedwriter and the printwriter
*/
public class buttonClick implements ActionListener{

@Override
public void actionPerformed(ActionEvent e) {
int retrievedValue = testMethod(enterField.getText());
try{
fw = new FileWriter(fileName, true);
bw = new BufferedWriter(fw);
output = new PrintWriter(bw);
}
catch(IOException g){
JOptionPane.showMessageDialog(frame, "File was not found.");
}

callSequence(retrievedValue);
}
  
}

/**
*Inner class that handles the WindowClose Event
* Closes the filewriter and the bufferedwriter
*/
public class CloseApp extends WindowAdapter{
public void windowClosing(WindowEvent e)
{
try{
fw.close();
bw.close();
}
catch(IOException f){}
}
  
public void windowClosed(WindowEvent e){
System.exit(0);
}
}
public static void main(String args[])
{
GUI g=new GUI();
}
}

Name it as GUI.java

Compile and using javac GUI.java

Now Run as java GUI

Before doing those compile Sequence file also as mentioned in the code below name it Sequence.java


public final class Sequence {

public static int counter;
  
private Sequence(){
counter = 0;
}
  
/**
*Computes the sequence values iteratively
*/
public static int computeIterative(int n){
int previous = 0;
int current = 1;
  
if(n==0){
return previous;
}
  
for(int i = 1; i < n; i++){
int result = (2 * current) + previous;
previous = current;
current = result;
getEfficiency();
int effI = counter;
}

return current;
}
  
/**
*Computes the sequence values recursively
*/
public static int computeRecursive(int n){
if(n == 0){
int result = 0;
getEfficiency();
return result;
}
  
if(n == 1){
int result = 1;
getEfficiency();
return result;
}

int num1 = computeRecursive(n-1);
int num2 = computeRecursive(n-2);
int newTerm = ((2 * num1) + num2);
getEfficiency();
int effR = counter;
return newTerm;
}
  
/**
*Calculates the efficiency for each method
*/
public static void getEfficiency(){
counter++;
}
  
/*
* Resets the counter variable
*/
public static void resetCounter(int a){
counter = a;
}
  
}// End Sequence.java

It will show the result in the run time window and the values are stored in a file named Output in ur PC

Go to the path where the program is stored and check for output.txt.

Ressult is shown on the applet window and when u open the text file output in ur pc wh

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote