my teacher got me this exercise to create a calculator which can store operations to a file and read them out later. I got the writer and I got the calculator; but the writer somehow overwrites everything in the file instead of adding. I tried bufferedWrtier append and now I am trying the Printwriter.
Debugging shows that my list is getting filled properly; yet the result is, that the saved file only contains the last input number and the last input operator.
public class Rechnung {
static Scanner scanner = new Scanner(System.in);
static double zahl1, zahl2, ergebnis;
static String op;
static boolean abbruch = true;
static File fileName = new File("Therme.txt");
static String numbers1;
static String eingabe;
public static void eingabe() {
while (abbruch) {
System.out.println("Geben Sie eine Zahl ein: ");
Listen.numbersDouble.add(scanner.nextDouble());
System.out.println("Bitte entscheiden Sie sich für '+', '-', '/', '*', '=': ");
op = scanner.next();
Listen.operators.add(op);
if (op.equals("=")) {
for (int i = 0; i < Listen.operators.size(); i++)
{
Writer.write(String.valueOf(Listen.numbersDouble.get(i)), Listen.operators.get(i));
}
abbruch = false;
}
else {
}
}
System.out.println(ausgabe());
}
public static double rechnen(String op, double zahl1, double zahl2)
{
switch (op) {
case "+":
ergebnis = zahl1 + zahl2;
return ergebnis;
case "-":
ergebnis = zahl1 - zahl2;
return ergebnis;
case "/":
ergebnis = zahl1 / zahl2;
return ergebnis;
case "*":
ergebnis = zahl1 * zahl2;
return ergebnis;
}
return ergebnis;
}
public static double ausgabe() {
zahl1 = Listen.numbersDouble.get(0);
for (int i = 1; i <= Listen.numbersDouble.size(); i++)
{
op = Listen.operators.get(i - 1);
if(op.equals("="))
{
return zahl1;
}
zahl2 = Listen.numbersDouble.get(i);
zahl1 = Rechnung.rechnen(op, zahl1, zahl2);
}
return -80085;
}
}
public class Writer {
public static void write(String string, String op) {
final String FILENAME = "C:\\Users\\nowackan\\eclipse-workspace\\Test.txt"; {
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(FILENAME);
bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
out.println(String.valueOf(string));
out.println(op);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Please note that I have barely a few weeks of programming experience and do not know any programming conventions.
To append content to an existing file, open file writer in append mode by passing second argument as true.
fw = new FileWriter(FILENAME,true);
bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
out.println(String.valueOf(string));
out.println(op);