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:
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;
}
}
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](http://img.homeworklib.com/images/024c61a6-c5f7-403b-a86f-a4f59744eb95.png?x-oss-process=image/resize,w_560)
Finish FormatJavaProgram.java that prompts the user for a file name and assumes that the file contains...
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...
FIRST: Write code that prompts the user for the name of a text file, opens that file if it exists and reads the file one line at a time printing each line to the screen. You must implement the file read in a try/catch block rather than throwing the exception on the main method. NEXT: Modify your code so that the program takes the name of two files from the command line, opens the first file if it exists for...
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...
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...
package Lab09; public class Lab09Driver { public static void main(String[] args) { new Lab09Driver(); } public Lab09Driver() { Scanner input = new Scanner(System.in); System.out.println("Would you like to load a previous file? (Y/N)"); String.choice = input.nextLine().trim().toUpperCase(); if (choice.charAt(0) == 'Y') { System.out.println("Enter the name of the file that you want to load:"); String.fileName = input.nextLine(); try { Scanner fileInput = new Scanner(new File(fileName)); while(fileInput.hasNextLine()){ String answer = fileInput.nextLine(); System.out.println(answer); }fileInput.close(); } catch (FileNotFoundException e) { System.out.println("Could not find the file, and...
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 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: Rewrite the following code to where the inputs are from a file. The file name will be from the input from the user scanner. CODE: import java.util.*; public class Q1 { public static int sumOD (int k) { int sumOD = 0; int in = k; while (in != 0) { int digitON = in % 10; sumOD += digitON; in /= 10; } return sumOD; } public static void main(String[] args) { int n, i, k; System.out.println("Enter...
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 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...