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

Overview These exercises will allow you to have some practice with basic Java fi

ID: 653065 • Letter: O

Question

Overview

These exercises will allow you to have some practice with basic Java file Input/Output. In addition, you will also have an opportunity to have more practice with methods and arrays.  

Objectives

Practice with programming fundamentals

Variables - Declaration and Assignment

Primitive types

Arithmetic Expressions

Simple keyboard input and text display output

Branching - if-elseif-else syntax

Loops - simple while loops, nested while loops

Methods - functions and procedures

ArrayLists - collections of variables

File I/O

Works towards the following Course Goals:

Competency with using basic coding features of a high-level imperative programming language

Competency with writing computer programs to implement given simple algorithms

Familiarity with designing simple text-oriented user interfaces

Overall Lab 13 Instructions

Using the instructions from Closed Lab 01, create a new folder named ClosedLab13. Unlike with previous labs, you will need to import the following file into your new lab folder. Follow the instructions from Clsoed Lab 01 to import this file into your ClosedLab13 folder.

Lab13a.java

In addition, you will need to place the following file in your ClosedLab13 folder to use as input for these exercises:

lab13aInput.txt

You will be writing a simple Java program that implements some basic file I/O operations. For the first exercise, you will write code that takes the name of a text file as input from the command line, opens that file if it exists and reads the file one line at a time. The program will reverse each line as it is read from the file and print the reversed line from the file to the console. For the second exercise, you will modify your code so that instead of printing each line reversed, the code prints the entire file reversed. For the third exercise you will modify your code one more time so that the program writes the output to a file instead of to the console.

Exercise 1 Description

Your code will prompt the user to enter a file name. If this file does not exist the program will produce an error message and exit. Otherwise the program will open the file and read a line from the file, reverse the line, and then print the line to the console. The program should process the entire file and terminate properly when the end of the file is reached.

Exercise 1 Sample Output

This is a sample transcript of what your program should do, assuming that the file lab13aInput.txt file provided above is used. Text in bold is expected input from the user rather than output from the program.

Enter an input name: lab13aInput.txt
ykcowrebbaJ

sevot yhtils eht dna ,gillirb sawT'
;ebaw eht ni elbmig dna eryg diD
,sevogorob eht erew ysmim llA
.ebargtuo shtar emom eht dnA

!nos ym ,kcowrebbaJ eht eraweB"
!hctac taht swalc eht ,etib taht swaj ehT
nuhs dna ,drib bujbuJ eht eraweB
"!hctansrednaB suoimurf ehT

:dnah ni drows laprov sih koot eH

Explanation / Answer

//Lab13a.java
package chegg;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Lab13a {
  
   private static Scanner scanner; // To read user inputs
   public static String reverse(String str) //reverse string function
   {
       String rev = ""; //declare reverse string to empty string
       for ( int i = str.length() - 1 ; i >= 0 ; i-- ) //read from last letter and add to front
   rev = rev + str.charAt(i);
      
       return rev;//return the reverse string
   }
   public static void main(String[] args) throws FileNotFoundException
   {
       scanner = new Scanner(System.in);
       System.out.print("Enter an input file name: ");
       String fileName = scanner.next();//reads input file name from user
      
      
       try //try block to find file exceptions
       {
           Scanner inFile = new Scanner(new File(fileName)); //scanner to read from file
           inFile.useDelimiter(" ");//set delimiter to be to read line by line
          
           while(inFile.hasNext())//till the file pointer is not empty read the file
           {
               String line = inFile.next();//read each line
               System.out.print(reverse(line));//reverse each line and display on screen
           }
          
           inFile.close();//close the file
       }
       catch(FileNotFoundException e) //on exception found display this error
       {
           System.out.println("There was a problem reading from "+fileName); //display error
       }
   }

}

------------------------------------------------------------------------------------------
//Lab13b.java
package chegg;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Stack;

public class Lab13b {

   private static Scanner scanner; // To read user inputs
   public static String reverse(String str) //reverse string function
   {
       String rev = ""; //declare reverse string to empty string
       for ( int i = str.length() - 1 ; i >= 0 ; i-- ) //read from last letter and add to front
   rev = rev + str.charAt(i);
      
       return rev;//return the reverse string
   }
   public static void main(String[] args) throws FileNotFoundException
   {
       scanner = new Scanner(System.in);
       System.out.print("Enter an input file name: ");
       String fileName = scanner.next();//reads input file name from user
      
      
       try //try block to find file exceptions
       {
           Scanner inFile = new Scanner(new File(fileName)); //scanner to read from file
           inFile.useDelimiter(" ");//set delimiter to be to read line by line
          
           Stack<String> fileData = new Stack<String>(); //stack to store each reversed data of file one by one
          
           while(inFile.hasNext())//till the file pointer is not empty read the file
           {
               String line = inFile.next();//read each line
               fileData.add(reverse(line));//reverse each line and push it to the stack
           }
          
           while(!fileData.empty())//till the stack is empty
           {
               System.out.print(fileData.pop());//pop each data to screen, thus printing the lines from bottom to top
           }
          
  
           inFile.close();//close the file
       }
       catch(FileNotFoundException e) //on exception found display this error
       {
           System.out.println("There was a problem reading from "+fileName);//display error
       }
   }
}


------------------------------------------------------------------------------------------------------------------
//Lab13c.java
package chegg;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.Stack;

public class Lab13c {

   private static Scanner scanner; // To read user inputs
   public static String reverse(String str) //reverse string function
   {
       String rev = ""; //declare reverse string to empty string
       for ( int i = str.length() - 1 ; i >= 0 ; i-- ) //read from last letter and add to front
   rev = rev + str.charAt(i);
      
       return rev;//return the reverse string
   }
   public static void main(String[] args) throws IOException
   {
       scanner = new Scanner(System.in);
       System.out.print("Enter an input file name: ");
       String inputFileName = scanner.next();//reads input file name from user
      
       System.out.print("Enter an output file name: ");
       String outputFileName = scanner.next();//reads output file name from user
      
       if(inputFileName.equals(outputFileName)) //if input file name and output file name are equal
       {
           System.out.println("ERROR! Your input file and output file MUST be different.");
       }
       else
       {
      
           try //try block to find file exceptions
           {
               Scanner inFile = new Scanner(new File(inputFileName)); //scanner to read from file
               inFile.useDelimiter(" ");//set delimiter to be to read line by line
              
               FileWriter outputFileWriter = new FileWriter(new File(outputFileName)); //file writer object
               BufferedWriter bufferedWriter = new BufferedWriter(outputFileWriter); //buffered writer object to the file
              
               Stack<String> fileData = new Stack<String>(); //stack to store each reversed data of file one by one
              
               while(inFile.hasNext())//till the file pointer is not empty read the file
               {
                   String line = inFile.next();//read each line
                   fileData.add(reverse(line));//reverse each line and push it to the stack
               }
              
               while(!fileData.empty())//till the stack is empty
               {
                   bufferedWriter.write(fileData.pop());//pop each data to screen, thus printing the lines from bottom to top
               }
              
      
               inFile.close();//close the file
               bufferedWriter.close(); //close buffered writer pointer
           }
           catch(FileNotFoundException e) //on exception found display this error
           {
               System.out.println("There was a problem reading from "+inputFileName);//display error
           }
           catch(IOException e) //on exception found display this error
           {
               System.out.println("Error writing to file "+outputFileName);//display error
           }
       }
   }
}
-------------------------------------------------------------------------------------------------

OUTPUT
-------------------------------------------------------------------------------------------------

1.

****************************************************************
Enter an input file name: lab13aInput.txt

ykcowrebbaJ

sevot yhtils eht dna ,gillirb sawT'
;ebaw eht ni elbmig dna eryg diD
,sevogorob eht erew ysmim llA
.ebargtuo shtar emom eht dnA

!nos ym ,kcowrebbaJ eht eraweB"
!hctac taht swalc eht ,etib taht swaj ehT
nuhs dna ,drib bujbuJ eht eraweB
"!hctansrednaB suoimurf ehT

:dnah ni drows laprov sih koot eH