Frage

So i passed a file into filewriter and then passed to printwriter. However, upon my assignments instructions im supposed to print these variables i pass to printwriter using a toString method in my superclass. This is for an assignment so thats why the rules are very clear as to how instructors wants the output to be.

 System.out.print("Please enter a file name: ");
    fileName = input.next();
    File fw = new File(fileName + ".txt");       

 AccountWithException acctException = new AccountWithException(fullName, balance, id, RATE);

 System.out.println(acctException.toString()); <---This works


 // pass object to printwriter and pw to write to the file
        pw = new PrintWriter(fw);
        // print to created file
        pw.println(firstName);
        pw.println(lastName);
        pw.println(balance);
        pw.println(id);
        pw.println(RATE);
        System.out.println(pw.toString());  <---Doesn't work. Only prints location and im supposed to somehow use the overloaded toString method to output the data within the file (i guess after its written)
War es hilfreich?

Lösung

You've actually given your own solution, but you need something like this -

pw = new PrintWriter(fw);
try {
  // print to created file
  // pw.println(firstName);
  // pw.println(lastName);
  // pw.println(balance);
  // pw.println(id);
  // pw.println(RATE);
  pw.println(acctException.toString()); // <-- Since 
                    // System.out.println(acctException.toString()); works!
} finally {
  pw.close(); // <-- Always close()!
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top