Java Assignment Help
Click here to load reader
-
Upload
programming-homework-help -
Category
Education
-
view
13 -
download
0
Transcript of Java Assignment Help
![Page 1: Java Assignment Help](https://reader038.fdocuments.in/reader038/viewer/2022100723/58f131cb1a28ab9c258b45f5/html5/thumbnails/1.jpg)
![Page 2: Java Assignment Help](https://reader038.fdocuments.in/reader038/viewer/2022100723/58f131cb1a28ab9c258b45f5/html5/thumbnails/2.jpg)
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](https://reader038.fdocuments.in/reader038/viewer/2022100723/58f131cb1a28ab9c258b45f5/html5/thumbnails/3.jpg)
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);
}
}
}