Question

Write a program that reverses a text file by using a stack. The user interface must...

Write a program that reverses a text file by using a stack. The user interface must consist of 2 list boxes and 3 buttons. The 3 buttons are: Read - reads the text file into list box 1. Reverse - reverses the items in list box 1 by pushing them onto stack 1, then popping them from stack 1 (in the reverse order) and adding them to list box 2. Write - writes the contents of list box 2 to a new text file. At first, only the Read button is enabled. After it is clicked, it is disabled and the Reverse button is enabled. After it is clicked, it is disabled and the Write button is enabled. After it is clicked, it is disabled. The name of the input text file is "input.txt". The input text file will contain no more than 100 lines of text. This fact is not needed by the program. It simply means that memory usage is not an issue. The name of the output text file is "output.txt". Notes: 1. The name of your main class should be ReverseFileViaStack. 2. Use the Java class library Stack class for your stack. 3. Use a border layout for your contents pane. 4. In the north region include the following title: Reverse a Text File via a Stack. 5. Use a panel in the center region to contain the 2 list boxes (side-by-side). 6. Place the 3 buttons in the south region. 7. A useful resource for this project is the week 5 video: Java GUI List Components

Example Programming Project Output Sample input file contents: a ab abc abcd abcde abcdef abcdefg abcdefgh abcdefghi abcdefghij abcdefghijk abcdefghijkl abcdefghijklm abcdefghijklmn abcdefghijklmno abcdefghijklmnop abcdefghijklmnopq abcdefghijklmnopqr abcdefghijklmnopqrs abcdefghijklmnopqrst abcdefghijklmnopqrstu abcdefghijklmnopqrstuv abcdefghijklmnopqrstuvw abcdefghijklmnopqrstuvwx abcdefghijklmnopqrstuvwxy abcdefghijklmnopqrstuvwxyz

0 0
Add a comment Improve this question Transcribed image text
Answer #1


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Stack;
import javax.swing.DefaultListModel;
import javax.swing.ListModel;

public class FileRead extends javax.swing.JFrame {

public FileRead() {
initComponents();
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList<>();
jScrollPane2 = new javax.swing.JScrollPane();
jList2 = new javax.swing.JList<>();
btnRead = new javax.swing.JButton();
btnReverse = new javax.swing.JButton();
btnWrite = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jScrollPane1.setViewportView(jList1);

jScrollPane2.setViewportView(jList2);

btnRead.setText("Read");
btnRead.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnReadActionPerformed(evt);
}
});

btnReverse.setText("Reverse");
btnReverse.setEnabled(false);
btnReverse.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnReverseActionPerformed(evt);
}
});

btnWrite.setText("Write");
btnWrite.setEnabled(false);
btnWrite.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnWriteActionPerformed(evt);
}
});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(41, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(48, 48, 48))
.addGroup(layout.createSequentialGroup()
.addGap(60, 60, 60)
.addComponent(btnRead)
.addGap(18, 18, 18)
.addComponent(btnReverse)
.addGap(18, 18, 18)
.addComponent(btnWrite)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnRead)
.addComponent(btnReverse)
.addComponent(btnWrite))
.addContainerGap(20, Short.MAX_VALUE))
);

pack();
}// </editor-fold>

private void btnReadActionPerformed(java.awt.event.ActionEvent evt) {
try {
//input file
File f = new File("H://inputfile.txt");
//model to add elements to the list
DefaultListModel input = new DefaultListModel();
//to read values from the file
Scanner sc = new Scanner(f);
while (sc.hasNext()) {
input.addElement(sc.next());
}
sc.close();
//adds elements to the list
jList2.setModel(input);
//disables read button
btnRead.setEnabled(false);
//enables reverse button
btnReverse.setEnabled(true);
} catch (FileNotFoundException ex) {
System.out.println(ex);
}

}   
Stack s = new Stack();

private void btnReverseActionPerformed(java.awt.event.ActionEvent evt) {   
ListModel input = new DefaultListModel<>();
DefaultListModel output = new DefaultListModel<>();
input = jList2.getModel();
//adds elements to the stack
for (int i = 0; i < input.getSize(); i++) {
s.push(input.getElementAt(i).toString());
}
//add elements to 2nd list from stack hence reversing them
for (int i = 0; i < input.getSize(); i++) {
output.addElement(s.pop());
}
jList1.setModel(output);
btnReverse.setEnabled(false);
btnWrite.setEnabled(true);
}

private void btnWriteActionPerformed(java.awt.event.ActionEvent evt) {   
PrintWriter p = null;
try {
// TODO add your handling code here:
ListModel output = new DefaultListModel<>();
output = jList1.getModel();
//output file
File f = new File("H://outputfile.txt");
f.createNewFile();
//writes data from 2nd list to file
p = new PrintWriter(f);
for (int i = 0; i < output.getSize(); i++) {
p.write(output.getElementAt(i).toString() + " \n");
}
} catch (FileNotFoundException ex) {
System.out.println(ex);
} catch (IOException ex) {
System.out.println(ex);
} finally {
p.close();
btnWrite.setEnabled(false);
btnRead.setEnabled(true);
}

}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FileRead.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FileRead.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FileRead.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FileRead.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FileRead().setVisible(true);
}
});
}

// Variables declaration - do not modify   
private javax.swing.JButton btnRead;
private javax.swing.JButton btnReverse;
private javax.swing.JButton btnWrite;
private javax.swing.JList<String> jList1;
private javax.swing.JList<String> jList2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
// End of variables declaration   
}

input file

a ab abc abcd abcde abcdef abcdefg abcdefgh abcdefghi abcdefghij abcdefghijk abcdefghijkl abcdefghijklm abcdefghijklmn abcdefghijklmno abcdefghijklmnop abcdefghijklmnopq abcdefghijklmnopqr abcdefghijklmnopqrs abcdefghijklmnopqrst abcdefghijklmnopqrstu abcdefghijklmnopqrstuv abcdefghijklmnopqrstuvw abcdefghijklmnopqrstuvwx abcdefghijklmnopqrstuvwxy abcdefghijklmnopqrstuvwxyz

output file

abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxy
abcdefghijklmnopqrstuvwx
abcdefghijklmnopqrstuvw
abcdefghijklmnopqrstuv
abcdefghijklmnopqrstu
abcdefghijklmnopqrst
abcdefghijklmnopqrs
abcdefghijklmnopqr
abcdefghijklmnopq
abcdefghijklmnop
abcdefghijklmno
abcdefghijklmn
abcdefghijklm
abcdefghijkl
abcdefghijk
abcdefghij
abcdefghi
abcdefgh
abcdefg
abcdef
abcde
abcd
abc
ab
a

ab abc abcd abcde Read Reverse Write

abcdefghijklmno ab abc abcd abcde abcdefghijklmnd Read Reverse Write

Add a comment
Know the answer?
Add Answer to:
Write a program that reverses a text file by using a stack. The user interface must...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Using java Create a simple queue class and a simple stack class. The queue and stack...

    Using java Create a simple queue class and a simple stack class. The queue and stack should be implemented as a linked list. Create three functions that utilize these data structures Write a function that opens a text file and reads its contents into a stack of characters. The program should then pop the characters from the stack and save them in a second text file. The order of the characters saved in the second file should be the reverse...

  • Write a program that uses a stack to reverse its inputs. Your stack must be generic...

    Write a program that uses a stack to reverse its inputs. Your stack must be generic and you must demonstrate that it accepts both String and Integer types. Your stack must implement the following methods: push, pop, isEmpty (returns true if the stack is empty and false otherwise), and size (returns an integer value for the number of items in the stack). You may use either an ArrayList or a LinkedList to implement your stack. Also, your pop method must...

  • ****THIS IS A 2 PART QUESTION! I ONLY NEED THE ANSWER TO PART 2 ON HOW...

    ****THIS IS A 2 PART QUESTION! I ONLY NEED THE ANSWER TO PART 2 ON HOW TO SEND THE DATA SERIALIZED**** Write a c# program that stores student grades in a text file and read grades from a text file.  The program has the following GUI: There are four buttons: Create File, Save Case, Close File and Load File.  Initially, only the Create File and Load File buttons are enabled.  If the user clicks the Create File button, a Save File Dialog window...

  • Write a program that opens a text file called input.txt and reads its contents into a...

    Write a program that opens a text file called input.txt and reads its contents into a stack of characters. The program should then pop the characters from the stack and save them in a second text file called output.txt. The order of the characters saved in the second file should be the reverse of their order in the first file. We don’t know the text file length. Input.txt This is a file is for test output.txt tset rof si elif...

  • Write a complete Python program with prompts for the user for the main text file (checks...

    Write a complete Python program with prompts for the user for the main text file (checks that it exists, and if not, output an error message and stop), for any possible flags (including none), and for any other input that this program may need from the user: split has an option of naming the smaller files head_tail list the first 10 lines (default) and the last 10 lines (default) in order of the given text file flag: -# output #...

  • JAVA Write a program that prompts the user to enter a file name, then opens the...

    JAVA Write a program that prompts the user to enter a file name, then opens the file in text mode and reads it. The input files are assumed to be in CSV format. The input files contain a list of integers on each line separated by commas. The program should read each line, sort the numbers and print the comma separated list of integers on the console. Each sorted list of integers from the same line should be printed together...

  • 4.3Learning Objective: To read and write text files. Instructions: This is complete program with one Java...

    4.3Learning Objective: To read and write text files. Instructions: This is complete program with one Java source code file named H01_43.java (your main class is named H01_43). Problem: Write a program that prompts the user for the name of a Java source code file (you may assume the file contains Java source code and has a .java filename extension; we will not test your program on non-Java source code files). The program shall read the source code file and output...

  • Write a calculator program using JavaScript in HTML in the same HTML file. (There will only...

    Write a calculator program using JavaScript in HTML in the same HTML file. (There will only be 1 HTML file containing everything that you use for this program.) *************JavaScript Functions should be written in the HTML <head> .............. </head> tag, **************** (Please be mindful of the formatting of the text of your program. Meaning that do not copy paste everything in a single line. Add clear comments for a better understanding of your program) as follows Assignment: create a form...

  • Write a Java program to read customer details from an input text file corresponding to problem...

    Write a Java program to read customer details from an input text file corresponding to problem under PA07/Q1, Movie Ticketing System The input text file i.e. customers.txt has customer details in the following format: A sample data line is provided below. “John Doe”, 1234, “Movie 1”, 12.99, 1.99, 2.15, 13.99 Customer Name Member ID Movie Name Ticket Cost Total Discount Sales Tax Net Movie Ticket Cost Note: if a customer is non-member, then the corresponding memberID field is empty in...

  • PYTHON PROGRAMMING LANGUAGE (NEEDED ASAP) Using a structured approach to writing the program: This section will...

    PYTHON PROGRAMMING LANGUAGE (NEEDED ASAP) Using a structured approach to writing the program: This section will guide you in starting the program in a methodical way. The program will display a window with GUI widgets that are associated with particular functions: Employee Payroll O X -- - - - - - - - - - - Show Payroll Find Employee by Name Highest Lowest Find Employee by Amount Write Output to Fie Cancel - -------- ------------- Notice that some of...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT