Question

Please program in JAVA: Program each option such as delete line and such. Your program will...

Please program in JAVA: Program each option such as delete line and such.

Your program will be a line editor. A line editor is an editor where all operations are performed by entering commands at the command line. Commands include displaying lines, inserting text, editing lines, cutting and pasting text, loading and saving files. For example, a session where the user enters three lines of text and saves them as a new file may appear as:

   Menu: m           Delete line:  dl
   Load file: l      Delete range:  dr
   Show all: sa      Copy range:  cr
   Show line:  sl    Paste lines:  pl
   Show range:  sr   Write to file:  w
   New line:  nl     Quit:  q
   Edit line:  el    Write and quit:  wq
->  nl

type line? (y/n):  y
1: this is the first line
type line? (y/n):  y
2: and a second line

type line? (y/n):  y
3: and this is the third line
type line? (y/n):  n

->  w

write to file:  test.txt

->  sa

1: this is the first line
2: and a second line
3: and this is the third line

->  q

The file created is:

this is the first line
and a second line
and this is the third line

The editor will first display a menu after which it will prompt for commands with "-> ". The commands which can be entered can be seen in the menu appearing in the example.

This web page was written with the line editor described here.

The Commands

If you run the program with no command line arguments it will begin with an empty document. If you give the name of an existing file as a command line argument it will open and load the contents of that file. You can exit the program with either the quit, q, or write and quit, wq, command.

Displaying the menu

The menu is displayed when the program starts. It can be displayed with the command m.

Reading and writing files

The load file command l will ask the user for a file name, open the file for reading, read the file contents into the editor and close the file. If there is already text in the editor it is discarded. The write file command w will write the contents of the editor to a file. If a file has previously been opened with the read file command that same file is used for writing. Otherwise, the program will prompt the user for a file name. For either the read or write file commands if the requested file cannot be opened an appropriate error message is displayed.

Displaying text

Text can be displayed with three commands: show all (sa), show range (sr), and show line (sl). All three commands display text with line numbers. Show all displays the entire document. Show range will ask the user a range of lines ("from" and "to") and will display the lines in that range. If the "to" line number is greater than the number of lines in the document lines up to the end of the document will be displayed. Show line will ask the user for a line number and display that line.

Entering new lines of text

New lines of text are entered using the new line command nl. Before entering a new line the program will ask type line? (y/n). If the user chooses yes the line will be accepted after the line number is displayed. If the document is empty the new line will be the first line (line 1) of the document. If the document is not empty the program will prompt the user to enter the line after which the new line will be placed. If the line number is out of range the program will not accept a new line. A new first line can be added by asking to add a line after (the non-existent) line 0. After the user has entered a line the program will continue asking for new lines until the user answers no. As the new lines are being entered they are added sequentially to the document. As the user begins to enter lines at the new line command the line after which the new line is being added is first displayed (unless the user is entering lines at the beginning of the document). Examples:

->  sa

1: this is the first line
2: and a second line
3: and this is the third line

->  nl
insert after line number:  1
inserting after:
this is the first line
type line? (y/n):  y
2: one and a half
type line? (y/n):  y

3: one and three quarters
type line? (y/n):  n

->  sa

1: this is the first line
2: one and a half
3: one and three quarters
4: and a second line
5: and this is the third line

->

The buffers

There are two buffers, the line buffer and the string buffer, used for moving blocks of text. The line buffer holds ranges of entire lines and the string buffer holds substrings of individual lines. Whenever a new range of lines is copied to the line buffer or a string is copied to the string buffer the previous contents of that buffer are deleted (but the other buffer is unaffected).

Moving ranges of lines

Blocks of lines can be moved using copy range, cr, and paste lines, pl. Copy range will ask the user for a range of line numbers ("from" and "to") and will copy the lines to the line buffer - the lines remain unchanged in the document. Paste lines will ask the user to enter the number of the line after which the lines from the line buffer will be pasted. The lines are then copied into the document - the line buffer is left unchanged. Ranges of lines are deleted with delete range, dr. Again, the user is asked for the range of line numbers to delete. The lines are then deleted (the line buffer is unchanged).

Editing a line of text

The edit line command, el will ask for the number of a line to edit then display the line preceded by a scale which allows the user to identify positions in the line by number (beginning with 0). Then the line menu is displayed and the program prompts for input.

->  el

line number:  3
0    5   10   15   20 
|----+----|----+----|-
one and three quarters

   Show line:  s
   Copy to string buffer:  c
   Cut:  t
   Paste from string buffer:  p
   Enter new substring:  e
   Delete substring:  d
   Quit line:  q
->  

The scale is at least as long as the line displayed. Operations chosen from the line menu will then operate on this chosen line until quit line, q.

Show line will display the line (again) with the scale. Quit returns to the main editor menu. The remaining commands edit the chosen line.

Copy to string buffer and Paste from string buffer work like copy range and paste lines but they work with the string buffer rather than the line buffer. Also, Paste from string buffer will insert the substring so that it begins at the specified position. (Thus it does an "insert before" where paste lines does an "insert after.")

->  c
0    5   10   15   20 
|----+----|----+----|-
one and three quarters
from position:  4
to position:  7
copied:
0    5   10   15   20 
|----+----|----+----|-
one and three quarters
    ^^^^
   Show line:  s
   Copy to string buffer:  c
   Cut:  t
   Paste from string buffer:  p
   Enter new substring:  e
   Delete substring:  d
   Quit line:  q
->  p
0    5   10   15   20
|----+----|----+----|-
one and three quarters
insert at position:  14
0    5   10   15   20   25
|----+----|----+----|----+
one and three and quarters

   Show line:  s
   Copy to string buffer:  c
   Cut:  t
   Paste from string buffer:  p
   Enter new substring:  e
   Delete substring:  d
   Quit line:  q
-> 

Delete substring, t, will prompt for a range of characters to delete, will display the string with the substring underlined, ask the user if the range is ok, and then delete the substring.

->  el

line number:  1
0    5   10   15   20 
|----+----|----+----|-
this is the first line

   Show line:  s
   Copy to string buffer:  c
   Cut:  t
   Paste from string buffer:  p
   Enter new substring:  e
   Delete substring:  d
   Quit line:  q
->  d

0    5   10   15   20 
|----+----|----+----|-
this is the first line
from position:  12
to position:  18
delete:
0    5   10   15   20 
|----+----|----+----|-

this is the first line
            ^^^^^^^
y/n:  y
0    5   10   15
|----+----|----+
this is the ine

Cut, t, combines copy to string buffer and delete substring. It copies the substring to the string buffer and removes it from the line.

Enter new substring, e, will allow the user to type new text into an existing line.

line number:  1
0    5   10   15   20
|----+----|----+----|-
this is the first line

   Show line:  s
   Copy to string buffer:  c
   Cut:  t
   Paste from string buffer:  p
   Enter new substring:  e
   Delete substring:  d
   Quit line:  q
->  e

0    5   10   15   20
|----+----|----+----|-
this is the first line
insert at position:  12
text:  very very
0    5   10   15   20   25   30
|----+----|----+----|----+----|-
this is the very very first line

Internals

You will define (among others) two classes: a Line class and a Document class. The Line class will hold the text of a line from the document in a field of type String and provide basic operations on a line. Some of these operations are insert a string into the line at a specified position, delete a substring, copy a substring, etc. The Line class will also have a field with the number of characters stored in the line. The Document class will hold an entire document (each line in one String) and provide basic operations such as inserting lines, deleting, copying, and pasting ranges of lines. It will also have a field with the number of lines currently in the document. Elsewhere in your program you will provide code for the operations (chosen by the user from the menu) which will then call the member functions of the Line and Document classes.

The document will be a doubly linked list of lines (Strings) with a dummy node. I.e., if there are 100 lines in the document there will be 101 nodes in the linked list - 100 holding text and one dummy node. This will make insertions and deletions much easier by eliminating special boundary conditions. Line numbers will not be stored with lines. Instead, every time a line number is needed (e.g. for display in show range and show all, finding positions for new line, etc.) it will be found by traversing the list and counting.

All strings will be Java Strings. Lines of text can be manipulated with concatenation and the substring methods:

String substring(int beginIndex)  // Returns a new string that is a
                                  // substring of this string.
String substring(int beginIndex, int endIndex)  // Returns a new string
                                                // that is a substring of
                                                // this string.

To accept a new line of user input you must use nextLine since reading with next stops accepting input at the first white space and text lines may contain white space. You must usenextLine for all keyboard input: nextLine does not mix well with next, nextInt, etc., so to read integer input you will first read a String and then convert it to an integer using Integer.parseInt.

You will do appropriate input validation. When choosing operations (in response to the "->" prompt) your program will only accept input as stated in the menu. When accepting integer input (line numbers, character positions in a line) your program will check for valid numbers and ranges.

Homework Answers

Answer #1

Editor.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

import utilities.LineList;

public class Editor {
  
   //Define static class-wide document, scanner, and copy buffers
   static Document doc;
   static Scanner in;
   static LineList lineCopyBuffer;
   static String stringCopyBuffer;
  
   //hold the path to the last opened file
   static String filePath;

   public static void main(String[] args) {
       //Create our copy buffers
       lineCopyBuffer = new LineList();
       stringCopyBuffer = "";
      
       //Create a blank document
       doc = new Document();
      
       //Create the input scanner
       in = new Scanner(System.in);
      
       //Initialize this to some default value
       filePath = "";
      
       //Show the menu for the first time
       showMenu();
      
       //Start the program loop
       while(true) {
          
           //Space things out a little so their easier to read
           System.out.println();
          
           //Wait for input...
           System.out.print("->\t");
           String command = in.nextLine();
          
           //Space things out a little so their easier to read
           System.out.println();
          
           //Go through the list of none commands looking for a match
           switch(command) {
           case "m"://Menu
               showMenu();
               break;
           case "l"://Load File
               load();
               break;
           case "sa"://Show All
               showAll();
               break;
           case "sl"://Show Line
               showLine();
               break;
           case "sr"://Show Range
               showRange();
               break;
           case "nl"://New Line
               newLine();
               break;
           case "el"://Edit Line
               editLine();
               break;
           case "dl"://Delete Line
               deleteLine();
               break;
           case "dr"://Delete Range
               deleteRange();
               break;
           case "cr"://Copy Range
               copyRange();
               break;
           case "pl"://Paste Lines
               pasteLines();
               break;
           case "w"://Write to File
               write();
               break;
           case "q"://Quit
               return;
           case "wq"://Write and Quit
               write();
               return;
           default:
               System.out.println("Unrecognized command");
           }
       }
   }

   static void showMenu() {
       //Just go through printing all the options out like they are in the example, using tabs for spacing
       System.out.println(""
               + "\tMenu: m\t\tDelete line: dl\n"
               + "\tLoad file: l\t\tDelete range: dr\n"
               + "\tShow all: sa\t\tCopy range: cr\n"
               + "\tShow line: sl\t\tPaste lines: pl\n"
               + "\tShow range: sr\t\tWrite to file: w\n"
               + "\tNew line: nl\t\tQuit: q\n"
               + "\tEdit line: el\t\tWrite and quit: wq");
   }
       //try to open a file buffered reader to read from the file
       BufferedReader inputStream = new BufferedReader(new FileReader(path));
       String line;
       try {
           line = inputStream.readLine();
          
           //Clear the document out so we are writing to a fresh document
           doc.clear();
          
           for(int i = 0; line != null; i++) {
               doc.insertLine(i, new Line(line));
               line = inputStream.readLine();
           }
          
           //Close the stream to avoid memory leaks
           inputStream.close();
          
           //We just loaded a file, so update filePath
           filePath = path;
       } catch (IOException e) {
           System.out.println("\tError reading file");
       }
   }
   static void load() {
       System.out.println("\tEnter file name to load");
       System.out.print("->");
       //Wait for them to type in a file
       String path = in.nextLine();
       //Try to read the file at path. if there is an exception, the file could not be found
       try {
           loadFileIntoDocument(path);
       } catch (FileNotFoundException e) {
           System.out.println("\tPath not found");
       }
   }
   static void showAll() {
       for(int i = 0; i < doc.length(); i++) {
           //Add one because doc is 0 indexed but user input is 1 indexed
           System.out.println((i + 1) + ":\t" + doc.getLine(i).getAll());
       }
   }
  
   static void showLine() {
       //Prompt for line number
       System.out.print("Which line?");
       String line = in.nextLine();
       //Try to turn what they typed into an int. if parseInt throws an exception then they messed up
       try {
           //Subtract one because doc is 0 indexed but user input is 1 indexed
           System.out.println(line + ":\t" + doc.getLine(Integer.parseInt(line) - 1).getAll());
       } catch (Exception e) {
           //What they typed in either wasn't a number or it was out of bounds of the document
           //Either way we don't care, just go back to the main menu
           System.out.println("Invalid line number");
       }
   }
   static void showRange() {
       //Prompt for start and end line numbers
       System.out.print("Starting line?\t");
       String start = in.nextLine();
       //Check and make sure this is valid input
       int startLine;
       try {
           startLine = Integer.parseInt(start);
           //If it's out of bounds of the doc, throw an exception so we go into the catch
           if((startLine <= 0) || (startLine > doc.length()))
               throw new Exception();
       } catch (Exception e) {
           System.out.println("Invalid line number");
           //Just skip over everything else in this loop and go back to the menu
           return;
       }
      
       System.out.print("Ending line?\t");
       String end = in.nextLine();
       //Check and make sure this is valid input
       int endLine;
       try {
           endLine = Integer.parseInt(end);
           //If it's out of bounds of the doc, throw an exception so we go into the catch
           if((endLine <= 0) || (endLine > doc.length()))
               throw new Exception();
       } catch (Exception e) {
           System.out.println("Invalid line number");
           //Just skip over everything else in this loop and go back to the menu
           return;
       }
      
       //Make sure starting line is not after ending line
       if(startLine > endLine) {
           System.out.println("Start line cannot be greater than end line");
           //skip over everything else in this cycle
           return;
       }
       //Actually print out the lines now
       for(int i = startLine; i <= endLine; i++) {
           //Subtract one because doc is 0 indexed but user input is 1 indexed
           System.out.println(i + ":\t" + doc.getLine(i - 1).getAll());
       }
   }
   static void newLine() {
       int lineNumber;
       //If the doc is empty then this is the first line, else prompt for where to put this line
       if(doc.length() == 0) {
           lineNumber = 0;
       }
       else {
           System.out.println("Insert after line number:\t");
           try {
               //Read the input and parse it into an int
               lineNumber = Integer.parseInt(in.nextLine());
               //If specified number is out of bounds throw an exception
               if((lineNumber < 0) || (lineNumber > doc.length()))
                   throw new Exception();
           } catch (Exception e) {
               //Either input wasn't a number or it was out of bounds
               System.out.println("Invalid line number");
               return;
           }
       }
       if(lineNumber == 0) {
           System.out.println("Inserting at first line");
       }
       else {
           System.out.println("Inserting after:");
           //Subtract one because doc is 0 indexed but user input is 1 indexed
           System.out.println(doc.getLine(lineNumber - 1).getAll());
       }
      
       //A loop for typing new lines. Only break out of this when user responds "n" to typing a new line
       while(true) {
           System.out.print("Type line? (y/n):\t");
           String response = in.nextLine();
          
           if(response.equals("y")) {
               //Add one because Document is 0 indexed but the editor is 1 indexed
               System.out.print((lineNumber + 1) + ":\t");
               //Insert whatever they type into the previously specified position in the doc
               doc.insertLine(lineNumber, new Line(in.nextLine()));
               //increment lineNumber so if we come through the loop again we are working on the next line
               lineNumber++;
           }
           else if(response.equals("n")) {
               //Just break out of this loop and go back to the main menu
               break;
           }
           else {
               System.out.println("Invalid response");
               //Skip to the next cycle of this loop
               continue;
           }
       }
   }
   static void editLine() {
       System.out.print("Which line?\t");
       //Read the lineNumber and verify the input just like i've done a few times already
       int lineNumber = 0;
       try {
           lineNumber = Integer.parseInt(in.nextLine());
           if((lineNumber <= 0) || (lineNumber > doc.length())) {
               throw new Exception();
           }
       } catch (Exception e) {
           System.out.println("Invalid line number");
           return;
       }
      
       //Store the line for later use (subtract 1 because of the 0 indexed vs 1 indexed problem)
       Line line = doc.getLine(lineNumber - 1);
      
       showLine(line);
      
       showLineMenu();
      
       while(true) {
           System.out.print("->\t");
           switch(in.nextLine()) {
           case "s"://Show line
               showLine(line);
               break;
           case "c"://Copy to string buffer
               copyToStringBuffer(line);
               break;
           case "t"://Cut
               cutToStringBuffer(line);
               showLine(line);
               break;
           case "p"://Paste from string buffer
               pasteFromStringBuffer(line);
               showLine(line);
               break;
           case "e"://Enter new substring
               enterNewSubstring(line);
               showLine(line);
               break;
           case "d"://Delete substring
               deleteSubstring(line);
               showLine(line);
               break;
           case "q"://quit line
               return;
           default:
               System.out.println("Unrecognized command");
           }
       }
   }
  
  
   static void showLineMenu() {
       System.out.println(""
               + "\tShow line: s\n"
               + "\tCopy to string buffer: c\n"
               + "\tCut: t\n"
               + "\tPaste from string buffer: p\n"
               + "\tEnter new substring: e\n"
               + "\tDelete substring: d\n"
               + "\tQuit Line: q");
   }
  
  
   static void showLine(Line line) {
       //for spacing
       System.out.println();
       for(int i = 0; i < line.length(); i++) {
           //Print the numbers divisible by 5 (0, 5, 10, 15, etc)
           if((i % 5) == 0) {
               System.out.print(i);
               //Because numbers >= 10 take two character spaces, we need to skip one character ahead when we print them to accomodate the extra character
               if(i >= 10) {
                   i++;
               }
           }
           else {
               System.out.print(" ");
           }
       }
       //Make sure to get each row on a new line
       System.out.println();
       //Print out the tick marks
       for(int i = 0; i < line.length(); i++) {
           //print a bar on the 10s and a + on the 5s. everything else gets a -
           if((i % 10) == 0) {
               System.out.print("|");
           }
           else if((i % 5) == 0) {
               System.out.print("+");
           }
           else {
               System.out.print("-");
           }
       }
       System.out.println();
       System.out.println(line.getAll());
       System.out.println();
   }
  
  
   static void copyToStringBuffer(Line line) {
       int start = 0;
       int end = 0;
      
       //Prompt for start position and validate input
       System.out.print("from position?\t");
       try {
           start = Integer.parseInt(in.nextLine());
           if((start < 0) || (start >= line.length())) {
               throw new Exception();
           }
       } catch (Exception e) {
           System.out.println("Invalid start position");
           return;
       }
      
       //Prompt for end position and validate input
       System.out.print("to position?\t");
       try {
           end = Integer.parseInt(in.nextLine());
           if((end < 0) || (end >= line.length())) {
               throw new Exception();
           }
       } catch (Exception e) {
           System.out.println("Invalid end position");
           return;
       }
      
       //Make sure start isnt after end
       if(start > end) {
           System.out.println("Start can't be after end");
           return;
       }
       stringCopyBuffer = new String(line.get(start, end));
   }
   static void cutToStringBuffer(Line line) {
       int start = 0;
       int end = 0;
      
       //Prompt for start position and validate input
       System.out.print("from position?\t");
       try {
           start = Integer.parseInt(in.nextLine());
           if((start < 0) || (start >= line.length())) {
               throw new Exception();
           }
       } catch (Exception e) {
           System.out.println("Invalid start position");
           return;
       }
      
       //Prompt for end position and validate input
       System.out.print("to position?\t");
       try {
           end = Integer.parseInt(in.nextLine());
           if((end < 0) || (end >= line.length())) {
               throw new Exception();
           }
       } catch (Exception e) {
           System.out.println("Invalid end position");
           return;
       }
      
       //Make sure start isnt after end
       if(start > end) {
           System.out.println("Start can't be after end");
           return;
       }
       stringCopyBuffer = new String(line.get(start, end));
       line.delete(start, end);
   }
   static void pasteFromStringBuffer(Line line) {
       System.out.print("Insert At?\t");
       int insertPosition = 0;
       //Once again wait for input and validate it
       try {
           insertPosition = Integer.parseInt(in.nextLine());
          
           if((insertPosition < 0) || (insertPosition > line.length())) {
               throw new Exception();
           }
       } catch (Exception e) {
           System.out.println("Invalid position");
           return;
       }
       line.insert(insertPosition, new String(stringCopyBuffer));
   }
   static void enterNewSubstring(Line line) {
       System.out.print("Insert At?\t");
       int insertPosition = 0;
       //again, wait for input and validate it
       try {
           insertPosition = Integer.parseInt(in.nextLine());
          
           if((insertPosition < 0) || (insertPosition > line.length())) {
               throw new Exception();
           }
       } catch (Exception e) {
           System.out.println("Invalid position");
           return;
       }
      
       System.out.print("text?\t");
       String text = in.nextLine();
       line.insert(insertPosition, text);
   }
  
   static void deleteSubstring(Line line) {
       int start = 0;
       int end = 0;
      
       //Prompt for start position and validate input
       System.out.print("from position?\t");
       try {
           start = Integer.parseInt(in.nextLine());
           if((start < 0) || (start >= line.length())) {
               throw new Exception();
           }
       } catch (Exception e) {
           System.out.println("Invalid start position");
           return;
       }
      
       //Prompt for end position and validate input
       System.out.print("to position?\t");
       try {
           end = Integer.parseInt(in.nextLine());
           if((end < 0) || (end >= line.length())) {
               throw new Exception();
           }
       } catch (Exception e) {
           System.out.println("Invalid end position");
           return;
       }
      
       //Make sure start isnt after end
       if(start > end) {
           System.out.println("Start can't be after end");
           return;
       }
      
       line.delete(start, end);
   }
   static void deleteLine() {
       System.out.print("Delete line number?\t");
       int line = 0;
       //wait for input and validate it
       try {
           line = Integer.parseInt(in.nextLine());
          
           if((line <= 0) || (line > doc.length())) {
               throw new Exception();
           }
       } catch (Exception e) {
           System.out.println("Invalid line number");
           return;
       }
      
       //Delete the line, converting from 1 indexed to 0 indexed
       doc.deleteLine(line - 1);
   }
   static void deleteRange() {
       int start = 0;
       int end = 0;
      
       //Prompt for start position and validate input
       System.out.print("from position?\t");
       try {
           start = Integer.parseInt(in.nextLine());
           if((start <= 0) || (start > doc.length())) {
               throw new Exception();
           }
       } catch (Exception e) {
           System.out.println("Invalid start position");
           return;
       }
      
       //Prompt for end position and validate input
       System.out.print("to position?\t");
       try {
           end = Integer.parseInt(in.nextLine());
           if((end <= 0) || (end > doc.length())) {
               throw new Exception();
           }
       } catch (Exception e) {
           System.out.println("Invalid end position");
           return;
       }
      
       //Make sure start isnt after end
       if(start > end) {
           System.out.println("Start can't be after end");
           return;
       }
      
       //Iterate through all the lines, removing each one
       for(int i = start; i <= end; i++) {
           //Convert from 1 indexed to 0 indexed
           doc.deleteLine(start - 1);
       }
   }
   static void copyRange() {
       int start = 0;
       int end = 0;
      
       //Prompt for start position and validate input
       System.out.print("from position?\t");
       try {
           start = Integer.parseInt(in.nextLine());
           if((start <= 0) || (start > doc.length())) {
               throw new Exception();
           }
       } catch (Exception e) {
           System.out.println("Invalid start position");
           return;
       }
      
       //Prompt for end position and validate input
       System.out.print("to position?\t");
       try {
           end = Integer.parseInt(in.nextLine());
           if((end <= 0) || (end > doc.length())) {
               throw new Exception();
           }
       } catch (Exception e) {
           System.out.println("Invalid end position");
           return;
       }
      
       //Make sure start isnt after end
       if(start > end) {
           System.out.println("Start can't be after end");
           return;
       }
      
       //Clear out the copy buffer
       lineCopyBuffer = new LineList();
       for(int i = end; i >= start; i--) {
           lineCopyBuffer.insertAt(0, new Line(doc.getLine(i - 1).getAll()));
       }
   }
   static void pasteLines() {
       System.out.print("Paste after line number?\t");
       int line = 0;
       //wait for input and validate it
       try {
           line = Integer.parseInt(in.nextLine());
          
           if((line <= 0) || (line > doc.length())) {
               throw new Exception();
           }
       } catch (Exception e) {
           System.out.println("Invalid line number");
           return;
       }
       doc.insertMultipleLines(line, lineCopyBuffer);
   }
   static void write() {
       //If filepath is still the default value, then we haven't opened another file and need to prompt for the file to store in
       String path = filePath;
       if(filePath == "") {
           System.out.println("File to write to?\t");
           path = in.nextLine();
       }
      
       try {
           BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
          
           //Iterate through every line in doc and write it to the file
           for(int i = 0; i < doc.length(); i++) {
               writer.write(doc.getLine(i).getAll());
               //Make sure to add a line break so each line is actually on a new line
               writer.write("\n");
           }
          
           //close the writer because we're done with it
           writer.close();
          
           //We just loaded a file so filePath needs to be updated with the path of the file we just loaded
           filePath = path;
       } catch (IOException e) {
           System.out.println("Could not write to file");
           //reset filePath because this path isnt working
           filePath = "";
       }
   }
}

Document.java

public class Document {
  
   LineList lines;

   public Document() {
       lines = new LineList();
   }
  
   public void insertLine(int lineNumber, Line lineToInsert) {
       lines.insertAt(lineNumber, lineToInsert);
   }
   public void insertMultipleLines(int startLineNumber, LineList linesToInsert) {
       for(int i = 0; i < linesToInsert.size(); i++) {
           insertLine(startLineNumber + i, new Line(linesToInsert.get(i).getAll()));
       }
   }
   public void deleteLine(int lineNumber) {
       lines.removeAt(lineNumber);
   }
   public void clear() {
       lines = new LineList();
   }
   public Line getLine(int lineNumber) {
       return lines.get(lineNumber);
   }
   public LineList getMultipleLines(int startLineNumber, int endLineNumber) {
       //Create the list we will return
       LineList result = new LineList();
       for(int currentLine = startLineNumber; currentLine <= endLineNumber; currentLine++) {
           //Insert at the end of the list (using the size function) so that the lines are in order
           result.insertAt(result.size(), lines.get(currentLine));
       }
       return result;
   }
  
   public int length() {
       return lines.size();
   }
  
   public String toString() {
       String str = "Document:\n";
       for(int i = 0; i < length(); i++) {
           str += lines.get(i).toString();
           //If this isn't the last string, add a new line
           if(i < (length() - 1)) {
               str += '\n';
           }
       }
       return str;
   }
}


note: due to limited character i cant able to upload following two files

Line.java
LineList.java

Know the answer?
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
Similar Questions
SOLUTION IN C## Write a program that reads every line in a text file, line by...
SOLUTION IN C## Write a program that reads every line in a text file, line by line. Obtain the name of the existing file and the name of the new (copy) of the file by prompting the user for both of these on the console. Make sure that the original file exists and can be read. If not, display a warning message and allow the user to either abort the program or enter a new file name. If the name...
Write a C program that prompts the user to enter a line of text on the...
Write a C program that prompts the user to enter a line of text on the keyboard then echoes the entire line. The program should continue echoing each line until the user responds to the prompt by not entering any text and hitting the return key. Your program should have two functions, writeStr and readLn, in addition to the main function. The text string itself should be stored in a char array in main. Both functions should operate on NUL-terminated...
language: JAVA the Problem Below are a series of problems you need to solve using recursive...
language: JAVA the Problem Below are a series of problems you need to solve using recursive methods. You will write a program that will read commands from an input file, with each command referring to one of the recursive problems to be executed. Each command will be followed (on the same line of input) by the respective parameters required for that problem. (15 points for main method) DescArrayCheck   Write a recursive method that checks whether an array of integers -...
Program Behavior Each time your program is run, it will prompt the user to enter the...
Program Behavior Each time your program is run, it will prompt the user to enter the name of an input file to analyze. It will then read and analyze the contents of the input file, then print the results. Here is a sample run of the program. User input is shown in red. Let's analyze some text! Enter file name: sample.txt Number of lines: 21 Number of words: 184 Number of long words: 49 Number of sentences: 14 Number of...
Write UNIX commands to perform the following tasks. Each task must use exactly one line of...
Write UNIX commands to perform the following tasks. Each task must use exactly one line of command. Unless stated otherwise, all files are assumed to be at your current working directory. a) (10 points) Print your current working directory into a file named file1 b) (10 points) Assume that your current working directory is NOT the same as your home directory. Print all file and subdirectory names of your home directory into a file named file2. c) (15 points) Copy...
Description: You will develop a small "text-based shell utility" ("ts") for Unix (or similar OS). A...
Description: You will develop a small "text-based shell utility" ("ts") for Unix (or similar OS). A common complaint of the most-used UNIX (text) shells (Bourne, Korn, C) is that it is difficult to remember (long) file names, and type "long" command names. A "menu" type shell allows a user to "pick" an item (file or command)from a "menu". You will display a simple menu, the following is a suggestion (you may change format): Current Working Dir: /home/os.progs/Me It is now:...
In this lab we will design a menu-based program. The program will allow users to decide...
In this lab we will design a menu-based program. The program will allow users to decide if they want to convert a binary number to base 10 (decimal) or convert a decimal number to base 2 (binary). It should have four functions menu(), reverse(), base2(), and base10(). Each will be outlined in detail below. A rubric will be included at the bottom of this document. Menu() The goal of menu() is to be the function that orchestrates the flow of...
can you please do this lab? use lunix or C program its a continuation of a...
can you please do this lab? use lunix or C program its a continuation of a previous lab. the previous lab: Unix lab 4: compile and link multiple c or c++ files Please do the following tasks step by step: create a new directory named by inlab4 enter directory inlab4 create a new file named by reverse.c with the following contents and then close the file: /*reverse.c */ #include <stdio.h> reverse(char *before, char *after); main() {       char str[100];    /*Buffer...
Part A. Input Validation (Name your C program yourLastName_yourFirstName_Lab4a.c) 1. Place the code you developed in...
Part A. Input Validation (Name your C program yourLastName_yourFirstName_Lab4a.c) 1. Place the code you developed in Lab 2 to obtain a diameter value from the user and compute the volume of a sphere (we assumed that to be the shape of a balloon) in a new program, and implement the following restriction on the user’s input: the user should enter a value for the diameter which is at least 8 inches but not larger than 60 inches. Using an if-else...
#include<iostream> #include<iomanip> using namespace std; int main() { //variables int choice; float radius,base,height,area; const double PI=3.14159;...
#include<iostream> #include<iomanip> using namespace std; int main() { //variables int choice; float radius,base,height,area; const double PI=3.14159; //repeat until user wants to quits while(true) { //menu cout<<endl<<endl<<"Geometry Calculator"<<endl<<endl; cout<<"1. Calculate the area of a circle"<<endl; cout<<"2. Calculate the area of a triangle"<<endl; cout<<"3. Quit"<<endl<<endl; //prompt for choice cout<<"Enter your choice(1-3): "; cin>>choice; cout<<endl; //if choice is circle if(choice==1) { cout<<"What is the radius of the circle? "; cin>>radius; //calculating area area=PI*radius*radius; cout<<endl<<"The area of the circle is "<<fixed<<setprecision(3)<<area<<endl; } //if choice...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT