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

Explanation / Answer

please rate - thanks

original code

import java.util.*;
import java.io.*;
public class formatProgram
{public static void main(String[] args)throws FileNotFoundException
{int count=0,i,j;
String filename,data;
Scanner in=new Scanner(System.in);
System.out.println("Enter the name of your input file: ");
filename=in.next();
Scanner input=new Scanner(new File(filename));
PrintStream output=new PrintStream(new File("newcode.java"));
while(input.hasNextLine())
{
data=input.nextLine();
for(i=0;i<count*4;i++)
output.print(" ");
output.println(data);
if(data.charAt(data.length()-1)=='{')
count++;
else if(data.charAt(data.length()-1)=='}')
count--;

}
}
}





more robust code --allows whitespaces after last characte, and blank lines


import java.util.*;
import java.io.*;
public class formatProgram
{public static void main(String[] args)throws FileNotFoundException
{int count=0,i,j;
String filename,data;
Scanner in=new Scanner(System.in);
System.out.print("Enter the name of your input file: ");
filename=in.next();
Scanner input=new Scanner(new File(filename));
PrintStream output=new PrintStream(new File("newcode.java"));
while(input.hasNextLine())
    {data=getAndPrintLine(input,output,count);
    count=checkLastCharacter(count,data);   
        
    }   
}
public static String getAndPrintLine(Scanner input,PrintStream output,int count)
{int i;
String data;
data=input.nextLine();
for(i=0;i<count*4;i++)
          output.print(" ");
     output.println(data);
return data;
}
public static int checkLastCharacter(int count,String data)
{int i=findLastChar(data);
if(i>=0) //not blank line
    {if(data.charAt(i)=='{')
        count++;
    else if(data.charAt(i)=='}')
        count--;
     }
return count;

}
public static int findLastChar(String data)
{int i;
for(i=data.length()-1;i>=0;i--)
      if(!Character.isWhitespace(data.charAt(i)))
           return i;
return -1;
}
}

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