所以我将一个文件传递给了文件编写器,然后传递给了printwriter。但是,根据我的分配指示我应该打印这些变量,我使用我的超类中的toString方法传递给printwriter。这是一个赋值,这就是为什么规则非常清楚教师如何想要输出。
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)
答案 0 :(得分:1)
你实际上已经给出了自己的解决方案,但是你需要这样的东西 -
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()!
}