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

Write a program that prompts the user for a file name, the file contains a Java

ID: 3771604 • Letter: W

Question

Write a program that prompts the user for a file name, the file contains a Java program. Your program should read the file and print to a file its contents properly indented. When you see a left- brace character { in the file, increase your indentation level by four spaces. When you see a right- brace character }, decrease your indentation level by four spaces. You may assume that the file has only one opening or closing brace per line, that every block statement (such as if or for) uses braces rather than omitting them, and that every relevant occurrence of a { or } character in the file occurs at the end of a line. This means, you are using K&R style blocks, as in:

while (i < 0) { ...

}

Consider using a class constant for the number of spaces to indent (4), so that it can easily be changed later.

Explanation / Answer

Here is the code for you. If you need further refinements, just get back to me.

import java.io.*;
import java.util.*;
class IndentingFile
{
public static final int INDENT = 4;
public static void main(String[] args) throws IOException
{
String line;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the name of the file to read in: ");
String inputFile = sc.next();
System.out.print("Enter the name of the file to write to: ");
String outputFile = sc.next();
BufferedReader inFile = new BufferedReader(new FileReader(new File(inputFile)));
BufferedWriter outFile = new BufferedWriter(new FileWriter(new File(outputFile)));
int count = 0;
while((line=inFile.readLine())!=null)
{
//System.out.println(line);
outFile.write(line);
outFile.newLine();
if(line.length() != 0 && line.charAt(line.length()-1) == '{')
count++;
if(line.length() != 0 && line.charAt(line.length()-1) == '}')
count--;

for(int i = 0; i < count*INDENT; i++)
outFile.write(" ");
  
}
outFile.close();
}
}

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