Question

Finish FormatJavaProgram.java that prompts the user for a file name and assumes that the file contains...

Finish FormatJavaProgram.java that prompts the user for a file name and assumes that the file contains a Java program. Your program should read the file (e.g., InputFile.java) and output its contents properly indented to ProgramName_Formatted.java (e.g., InputFile_Formatted.java). (Note: It will be up to the user to change the name appropriately for compilation later.)

When you see a left-brace character ({) in the file, increase your indentation level by NUM_SPACES spaces. When you see a right-brace character (}), decrease your indentation level by NUM_SPACES 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.

Optional added challenges:

  • Consider instance with opening and closing braces on same line (such as } else if(){).
  • Make your program work correctly with input files that contain statements like System.out.println("} else if(){");

Code Below:

import java.io.*;
import java.util.*;

/**
* Program that takes an unformatted Java program and prints out the same Java
* program with proper indentation.
*
*
*/
public class FormatJavaProgram {

/** Constant representing number of spaces to indent */
public static final int NUM_SPACES = 4;

/**
* Starts the program
*
* @param args An array of command line arguments
*/
public static void main(String[] args) {
userInterface();
}

/**
* Program's user interface.
*/
public static void userInterface() {
// Create null objects as placeholders for scope
// We specifically want a File object since we are basing the
// output file's name on the input file's name
File file = null;
Scanner inputFile = null;

Scanner console = new Scanner(System.in);

// While we have not gotten a valid file that can make a Scanner
// we'll get an input file, and try to create a Scanner.
while (inputFile == null) {
file = getInputFile(console);
inputFile = getInputScanner(file);
}

// Create a PrintStream based on the valid file
// passed in by the user
PrintStream outputFile = getOutputPrintStream(file);

// If the PrintStream could be created, then process the
// Java file.
if (outputFile != null) {
processJavaFile(inputFile, outputFile);
} else {
System.out.println("Output file cannot be written");
}
}

/**
* Returns a File object from the file name entered by the user
*
* @param console Scanner for console
* @return a File representing the file on the OS entered by the user
*/
public static File getInputFile(Scanner console) {
File file = null;
// TODO: write method
return file;
}

/**
* Returns a Scanner for the specified file, or null if the file does not
* exist.
*
* @param file the File entered by the user
* @return a Scanner to read the file
*/
public static Scanner getInputScanner(File file) {
Scanner inputFile = null;
// TODO: write method that uses a try/catch. Catch should print error
// message, but NOT end program.
return inputFile;
}

/**
* Returns a PrintStream for the specified file, or null if the file cannot
* be created. PrintStream should be format of ProgramName_Formatted.java
* based on name of file.
*
* @param file the File entered by the user
* @return a PrintStream to print to the file.
*/
public static PrintStream getOutputPrintStream(File file) {
PrintStream outputFile = null;
// HINT: use File getName() to get name of file to use to set up name of
// formatted file.

// TODO: write method that uses a try/catch. Catch should print error
// message, but NOT end program.
return outputFile;
}

/**
* Processes a Java file and provides the proper indentation
*
* @param inputFile the Java file to process
* @param outputFile the file to write the formated code to
*/
public static void processJavaFile(Scanner inputFile, PrintStream outputFile) {
int indentLevels = 0;
while (inputFile.hasNextLine()) {
String line = inputFile.nextLine().trim(); // trim() cuts of leading
// and ending whitespace

//TODO: Along with updating the tests below, you will also need to consider how
// you will need to update indentLevels within each block of the if/else structure
  
// TODO: For added challenge, uncomment (remove /* and */) and add
// condition for opening and closing braces on same line
/*
if (true) { // If line contains both } and { like a catch line or else
// TODO: update test from "true"
  
outputFile.println(getFormattedLine(line, indentLevels));
  
} else
*/
if (true) { // If the line only contains a closing bracket
// TODO: update test from "true"

outputFile.println(getFormattedLine(line, indentLevels));

} else if (true) { // If the line only contains an opening bracket
// TODO: update test from "true"

outputFile.println(getFormattedLine(line, indentLevels));

} else { // All other lines

outputFile.println(getFormattedLine(line, indentLevels));

}
}
}

/**
* Returns a line of Java code formatted to the proper indentation
*
* @param line the line to format
* @param indentLevels the number of levels of indentation
* @return the formatted line
*/
public static String getFormattedLine(String line, int indentLevels) {
String formattedLine = "";

return formattedLine;
}

}

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


Please let me know if you have any doubts or you want me to modify the answer. And if you find this answer useful then don't forget to rate my answer as thumps up. Thank you! :)

import java.io.*;
import java.util.*;


public class FormatJavaProgram {

    public static final int NUM_SPACES = 4;

    public static void main(String[] args) {
        userInterface();
    }

    public static void userInterface() {
        Scanner console = new Scanner(System.in);

        Scanner fileReader = getInputScanner(console);

        PrintStream fileWriter = getOutputPrintStream(console);

        processJavaFile(fileReader, fileWriter);

        fileWriter.close();
        fileReader.close();
        console.close();
    }


    public static Scanner getInputScanner(Scanner console) {
        Scanner file = null;
        try {
            File f;
            do {
                System.out.print("Enter Java File to Format: ");
                String input = console.nextLine();
                f = new File(input);

            } while (!f.exists());
            file = new Scanner(f);

        } catch (FileNotFoundException ex) {
        }
        return file;
    }


    public static PrintStream getOutputPrintStream(Scanner console) {
        File f;
        PrintStream file = null;
        while (file == null) {
            try {
                System.out.print("Enter Output file: ");
                String input = console.nextLine();
                f = new File(input);
                file = new PrintStream(f);
            } catch (FileNotFoundException ex) {
            }
        }

        return file;

    }

  
    public static void processJavaFile(Scanner input, PrintStream output) {
        int indentLevels = 0;
        while (input.hasNextLine()) {
            String line = input.nextLine().trim();

            if (line.contains("}") && line.contains("{")) {
                output.println(getFormattedLine(line, indentLevels));

            } else if (line.contains("}")) {
                output.println(getFormattedLine(line, indentLevels));
                indentLevels--;

            } else if (line.contains("{")) {
                indentLevels++;
                if (line.contains("public class")) {
                    indentLevels--;
                }
                output.println(getFormattedLine(line, indentLevels));

            } else if (line.contains("import")) {
                output.println((getFormattedLine(line, indentLevels)));

            } else {
                indentLevels++;
                output.println((getFormattedLine(line, indentLevels)));
                indentLevels--;

            }
        }
    }

  
    public static String getFormattedLine(String line, int indentLevels) {
        String formattedLine = "";
        for (int i = 0; i < indentLevels; i++) {
            for (int j = 0; j < NUM_SPACES; j++) {
                formattedLine += " ";
            }
        }
        formattedLine += line;
        return formattedLine;
    }

}
FormatJavaProgram [/ldeaProjects/FormatJava Program] -/src/FormatJava Program.java [FormatJava Program] Format JavaProgram Fo

Add a comment
Know the answer?
Add Answer to:
Finish FormatJavaProgram.java that prompts the user for a file name and assumes that the file contains...
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
  • Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file...

    Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file doesn’t exist. You will process through the file skipping any text or real (double) numbers. You will print the max, min, sum, count, and average of the integers in the file. You will want to create test files that contain integers, doubles, and Strings. HINT: Use hasNextInt() method and while loop. You may also want to use Integer.MAX_VALUE and Integer.MIN_VALUE for the initialization of...

  • Lab 19 - History of Computer Science, A File IO Lab FIRST PART OF CODING LAB:...

    Lab 19 - History of Computer Science, A File IO Lab FIRST PART OF CODING LAB: Step 0 - Getting Starting In this program, we have two classes, FileIO.java and FileReader.java. FileIO.java will be our “driver” program or the main program that will bring the file reading and analysis together. FileReader.java will create the methods we use in FileIO.java to simply read in our file. Main in FileIO For this lab, main() is provided for you in FileIO.java and contains...

  • Write a program in Java that prompts a user for Name and id number. and then...

    Write a program in Java that prompts a user for Name and id number. and then the program outputs students GPA MAIN import java.util.StringTokenizer; import javax.swing.JOptionPane; public class Main {    public static void main(String[] args) {                       String thedata = JOptionPane.showInputDialog(null, "Please type in Student Name. ", "Student OOP Program", JOptionPane.INFORMATION_MESSAGE);        String name = thedata;        Student pupil = new Student(name);                   //add code here       ...

  • Homework Assignment on Mimir: Read in a file "numbers.txt" into a Java program. Sum up all...

    Homework Assignment on Mimir: Read in a file "numbers.txt" into a Java program. Sum up all the even numbers over 50. Print the result to the console using System.out.println(); The file will only have numbers. Code: import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Scanner; /** * * @author David */ public class ReadingFiles {     /**      * @param args the command line arguments      */     public static void main(String[] args) throws FileNotFoundException {         // TODO code application logic here...

  • JAVA project PLEASE complete/ create project with comments in the programming explaining everything Text file Year...

    JAVA project PLEASE complete/ create project with comments in the programming explaining everything Text file Year of storm/ Name of storm/ mmdd storm started/ mmdd storm ended/ magnitude of storm/ //made up data 2004/Ali/1212/1219/1 2003/Bob/1123/1222/3 1980/Sarah/0123/0312/0 1956/Michael/1211/1223/4 1988/Ryan/0926/1019/ 1976/Tim/0318/1010/0 2006/Ronald/0919/1012/2 1996/Mona/0707/0723/1 2000/Kim/0101/0201/1 2001/Jim/1101/1201/3 Text file Class storm{ private String nameStorm; private int yearStorm; private int startStorm; private int endStorm; private int magStorm; public storm(String name, int year, int start, int end, int mag){ nameStorm = name; yearStorm = year; startStorm...

  • Modify the below Java program to use exceptions if the password is wrong (WrongCredentials excpetion). import java.util....

    Modify the below Java program to use exceptions if the password is wrong (WrongCredentials excpetion). import java.util.HashMap; import java.util.Map; import java.util.Scanner; class Role { String user, password, role; public Role(String user, String password, String role) { super(); this.user = user; this.password = password; this.role = role; } /** * @return the user */ public String getUser() { return user; } /** * @param user the user to set */ public void setUser(String user) { this.user = user; } /** *...

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

  • Complete the code: package hw4; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.Scanner; /* * This...

    Complete the code: package hw4; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.Scanner; /* * This class is used by: * 1. FindSpacing.java * 2. FindSpacingDriver.java * 3. WordGame.java * 4. WordGameDriver.java */ public class WordGameHelperClass { /* * Returns true if an only the string s * is equal to one of the strings in dict. * Assumes dict is in alphabetical order. */ public static boolean inDictionary(String [] dict, String s) { // TODO Implement using binary search...

  • Fibtester: package fibtester; // Imported to open files import java.io.File; // Imported to use the exception...

    Fibtester: package fibtester; // Imported to open files import java.io.File; // Imported to use the exception when files are not found import java.io.FileNotFoundException; // Imported to write to a file import java.io.PrintWriter; // Imported to use the functionality of Array List import java.util.ArrayList; // Imported to use the exceptions for integer values import java.util.NoSuchElementException; // Imported to use when the array is out of bounds import java.lang.NullPointerException; // Imported to take input from the user import java.util.Scanner; public class FibTester...

  • How to complete these methods: /**    * Returns a reference to the course with title equals to the argument. This    * m...

    How to complete these methods: /**    * Returns a reference to the course with title equals to the argument. This    * method searches in the courses stored in the HashMap {@code courses} to find    * the course whose title equals to the argument {@code title}. If the course is    * not found, {@code null} is returned.    *    * @param title the title of the course    * @return a reference to the course, or {@code null} if the course is not   ...

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