Java Assignment Help

3

Click here to load reader

Transcript of Java Assignment Help

Page 1: Java Assignment Help
Page 2: Java Assignment Help

Line manipulations programming using Array List in Java

Description: This is a program that converts a next line brace

formatted program into the end of line brace style program.

importjava.util.Scanner;

importjava.util.ArrayList;

import java.io.*;

public class ChangeStyle {

public static void main(String[] args) {

Scanner console = new Scanner(System.in);

String filename = null;

Scanner input = null;

while (true) {

// try to open the file

// if cannot open the file, loop to prompt again

try {

System.out.print("Enter filename: ");

filename = console.nextLine().trim();

input = new Scanner(new File(filename));

break;

} catch (IOException e) {

System.out.println("Bad filename");

}

}

// to save the output lines

ArrayList<String> lines = new ArrayList<String>();

while (input.hasNextLine()) {

String line1 = input.nextLine();

String line2 = line1.trim();

if (line2.startsWith("{")) {

// a line starts with {, move it to the previous line

int index = line1.indexOf('{');

line1 = line1.substring(0, index) + " " +

line1.substring(index + 1);

line2 = line1.trim();

if (!lines.isEmpty()) {

String previous = lines.remove(lines.size() - 1);

previous = previous + " {";

lines.add(previous);

}

if (line2.length() > 0) {

lines.add(line1);

}

} else {

// otherwise, not start with {

Page 3: Java Assignment Help

lines.add(line1);

}

}

input.close();

// save into the the original file

try {

PrintStream out = new PrintStream(new FileOutputStream(filename));

for (String line : lines) {

out.println(line);

}

out.close();

} catch (IOException e) {

System.out.println("could not save into file " + filename);

}

}

}