import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Primzahlsucher {
public static void main(String[] args) {
int n = 5; Trace trace = new Trace(); trace.register("n", n);
for (int i = 2; i <= n; i++) { trace.register("i", i);
boolean istPrimzahl = true; trace.register("istPrimzahl", istPrimzahl);
for (int j = 2; j < i && istPrimzahl == true; j++) { trace.register("j", j);
if (i % j == 0) {
istPrimzahl = false; trace.register("istPrimzahl", istPrimzahl);
}
}
if (istPrimzahl) {
System.out.println(i + " ist eine Primzahl.");
}
}
trace.print();
}
private static class Trace {
record Entry(int lineNumber, String variableName, Object value) {}
private List<Entry> entries = new ArrayList<>();
public void register(String variableName, Object value) {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
int lineNumber = stackTrace[2].getLineNumber();
entries.add(new Entry(lineNumber, variableName, value));
}
public void print() {
List<String> variables = entries.stream().map(Entry::variableName).distinct().toList();
List<String> columnNames = Stream.concat(Stream.of("Zeile"), variables.stream()).toList();
String lineFormat = columnNames.stream().map(name -> "%%%ds".formatted(name.length()))
.collect(Collectors.joining(" | ", "", "%n"));
System.out.print(lineFormat.formatted(columnNames.toArray()));
Map<String, Object> currentState = new HashMap<>();
for (Entry entry : entries) {
currentState.put(entry.variableName, entry.value);
List<String> rowValues = new ArrayList<>();
rowValues.add(String.valueOf(entry.lineNumber));
for (String column : variables) {
Object value = currentState.get(column);
String output = value == null ? "-" : String.valueOf(value);
rowValues.add(output);
}
System.out.printf(lineFormat, rowValues.toArray());
}
}
}
}