Question

Overview These exercises will allow you to have some practice with basic Java file Input/Output. In...

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

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

//Lab13a.java
package abc;

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("\n");//set delimiter to be \n 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 abc;

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("\n");//set delimiter to be \n 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 abc;

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("\n");//set delimiter to be \n 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

Add a comment
Know the answer?
Add Answer to:
Overview These exercises will allow you to have some practice with basic Java file Input/Output. In...
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
  • C++ (1) Write a program to prompt the user for an input and output file name....

    C++ (1) Write a program to prompt the user for an input and output file name. The program should check for errors in opening the files, and print the name of any file which has an error, and exit if an error occurs. For example, (user input shown in caps in first line, and in second case, trying to write to a folder which you may not have write authority in) Enter input filename: DOESNOTEXIST.T Error opening input file: DOESNOTEXIST.T...

  • (Java) Rewrite the following exercise below to read inputs from a file and write the output...

    (Java) Rewrite the following exercise below to read inputs from a file and write the output of your program in a text file. Ask the user to enter the input filename. Use try-catch when reading the file. Ask the user to enter a text file name to write the output in it. You may use the try-with-resources syntax. An example to get an idea but you need to have your own design: try ( // Create input files Scanner input...

  • Please write this in C. Write this code in Visual Studio and upload your Source.cpp file for checking (1) Write a program to prompt the user for an output file name and 2 input file names. The progra...

    Please write this in C. Write this code in Visual Studio and upload your Source.cpp file for checking (1) Write a program to prompt the user for an output file name and 2 input file names. The program should check for errors in opening the files, and print the name of any file which has an error, and exit if an error occurs opening any of the 3 For example, (user input shown in caps in first line) Enter first...

  • 16.43 Lab 13C: Palindromes with Files and Functions Overview This is a demonstration of reading and...

    16.43 Lab 13C: Palindromes with Files and Functions Overview This is a demonstration of reading and writing files, along with using user-defined functions. Objectives Be able to read from an input file, perform string manipulation on each line of the file within a function, and write to an output file. Provided input file: A single input file named myinput.txt is provided that contains a few lines of text. bob sees over the moon never odd or even statistics dr awkward...

  • The input file should be called 'data.txt' and should be created according to the highlighted instructions...

    The input file should be called 'data.txt' and should be created according to the highlighted instructions below. Note that even though you know the name of the input file, you should not hard-code this name into your program. Instead, prompt the user for the name of the input file. The input file should contain (in order): the weight (a number greater than zero and less than or equal to 1), the number, n, of lowest numbers to drop, and the...

  • You will be writing some methods that will give you some practice working with Lists. Create...

    You will be writing some methods that will give you some practice working with Lists. Create a new project and create a class named List Practice in the project. Then paste in the following code: A program that prompts the user for the file names of two different lists, reads Strings from two files into Lists, and prints the contents of those lists to the console. * @author YOUR NAME HERE • @version DATE HERE import java.util.ArrayList; import java.util.List; import...

  • In Python Please! 16.42 Lab 13B: Palindromes with Files Overview This is a demonstration of reading...

    In Python Please! 16.42 Lab 13B: Palindromes with Files Overview This is a demonstration of reading and writing files. Objectives Be able to read from an input file, perform string manipulation on each line of the file, and write to an output file. Provided input file: A single input file named myinput.txt is provided that contains a few lines of text. bob sees over the moon never odd or even statistics dr awkward Provided output file: A single output file...

  • Basic C program Problem: In this assignment, you have to read a text file (in.txt) that...

    Basic C program Problem: In this assignment, you have to read a text file (in.txt) that contains a set of point coordinates (x,y). The first line of the file contains the number of points (N) and then each line of the file contains x and y values that are separated by space. The value of x and y are an integer. They can be both negative and positive numbers. You have to sort those points in x-axis major order and...

  • 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...

  • *Java* You will write a program to do the following: 1. Read an input file with...

    *Java* You will write a program to do the following: 1. Read an input file with a single line of text. Create a method named load_data. 2. Determine the frequency distribution of every symbol in the line of text. Create a method named 3. Construct the Huffman tree. 4. Create a mapping between every symbol and its corresponding Huffman code. 5. Encode the line of text using the corresponding code for every symbol. 6. Display the results on the screen....

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