Instructions
Requirements and Specifications
Source Code
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
private static final String INPUT_FILENAME = "input.txt";
public static void main(String[] args) throws Exception {
try (Scanner scanner = new Scanner(new File(INPUT_FILENAME))) {
List<List<double[]>> data = new ArrayList<>();
int section = 0;
while (scanner.hasNextLine()) {
List<double[]> coefs = new ArrayList<>();
int length = -1;
boolean first = true;
String line = scanner.nextLine().trim();
section++;
while (!"*".equals(line)) {
String[] parts = line.split(",");
double[] coefRow = new double[parts.length];
for (int i = 0; i < parts.length; i++) {
coefRow[i] = Double.parseDouble(parts[i]);
}
if (first) {
length = coefRow.length;
first = false;
} else if (length >= 0) {
if (coefRow.length != length) {
length = -1;
}
}
coefs.add(coefRow);
if (scanner.hasNextLine()) {
line = scanner.nextLine();
} else {
line = "*";
}
}
if (length < 0) {
System.out.println("Section #" + section + " will be disregarded");
} else {
data.add(coefs);
}
}
System.out.println("------------------------------------------------------------------------------------------------------------------");
System.out.println("Poly No. Degree # vars Function");
System.out.println("------------------------------------------------------------------------------------------------------------------");
int counter = 1;
for(List<double[]> row : data) {
StringBuilder builder = new StringBuilder();
builder.append(String.format("%5d", counter));
int degree = row.get(0).length - 1;
builder.append(String.format("%7d", degree));
builder.append(String.format("%8d", row.size()));
builder.append(" f(x) = ");
for(int i = 0; i<row.size(); i++) {
double[] poly = row.get(i);
if (i > 0) {
builder.append(" + ");
}
builder.append("( ");
int deg = degree;
for(double d : poly) {
if (deg > 0) {
builder.append(String.format("%.2fx%d^%d + ", d, i+1,deg));
}
else {
builder.append(String.format("%.2f", d));
}
deg--;
}
builder.append(" )");
}
System.out.println(builder);
counter++;
}
}
}
}