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: 3771603 • 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

Answer :

import java.util.*;

import java.io.*;
class ProgramIndentation {

public static final int SPACES = 4;

public static void main(String[] args) throws FileNotFoundException {

  
Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name(.java file only):");
String file_name = sc.nextLine();
Scanner input = new Scanner(new File(file_name));
  
String firstLine = input.nextLine();
System.out.print(firstLine);
  
while(input.hasNextLine()) {
  
String next_read = input.nextLine();
  
if(next_read.contains(Character.toString('{'))) {
  
}
/*next_read = next_read.trim();if you want to align the content as left aligned you

can un comment it */

System.out.println(next_read);
     
}
}
}

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