javaIO流程序出现了错误,请高手详细指点!
这是我的作业上的java代码。运行后出现了错误:
Exception in thread "main" java.io.NotSerializableException: StoreLoanObjects$Loan
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at StoreLoanObjects.main(StoreLoanObjects.java:23)import java.io.*;
代码:
public class StoreLoanObjects implements java.io.Serializable{
public StoreLoanObjects() {
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) throws ClassNotFoundException,IOException{
// TODO Auto-generated method stub
StoreLoanObjects a = new StoreLoanObjects();
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("Exercise19_6.dat",true));
Loan loanA = a.new Loan(2.5,4,1000);
Loan loanB = a.new Loan(2.5,2,1000);
Loan loanC = a.new Loan(2.5,4,5000);
Loan loanD = a.new Loan(6.5,4,1000);
Loan loanE = a.new Loan(6.5,2,1000);
output.writeObject(loanA);
output.writeObject(loanB);
output.writeObject(loanC);
output.writeObject(loanD);
output.writeObject(loanE);
output.close();
}
/** Loan class */
class Loan {
private double annualInterestRate;
private int numberOfYears;
private double loanAmount;
private java.util.Date loanDate;
/** Default constructor */
public Loan() {
this(2.5, 1, 1000);
}
/** Construct a loan with specified annual interest rate,
number of years and loan amount
*/
public Loan(double annualInterestRate, int numberOfYears,
double loanAmount) {
this.annualInterestRate = annualInterestRate;
this.numberOfYears = numberOfYears;
this.loanAmount = loanAmount;
loanDate = new java.util.Date();
}
/** Return annualInterestRate */
public double getAnnualInterestRate() {
return annualInterestRate;
}
/** Set a new annualInterestRate */
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
/** Return numberOfYears */
public int getNumberOfYears() {
return numberOfYears;
}
/** Set a new numberOfYears */
public void setNumberOfYears(int numberOfYears) {
this.numberOfYears = numberOfYears;
}
/** Return loanAmount */
public double getLoanAmount() {
return loanAmount;
}
/** Set a newloanAmount */
public void setLoanAmount(double loanAmount) {
this.loanAmount = loanAmount;
}
/** Find monthly payment */
public double getMonthlyPayment() {
double monthlyInterestRate = annualInterestRate / 1200;
double monthlyPayment = loanAmount * monthlyInterestRate / (1 -
(Math.pow(1 / (1 + monthlyInterestRate), numberOfYears * 12)));
return monthlyPayment;
}
/** Find total payment */
public double getTotalPayment() {
double totalPayment = getMonthlyPayment() * numberOfYears * 12;
return totalPayment;
}
/** Return loan date */
public java.util.Date getLoanDate() {
return loanDate;
}
}
}
不知是什么问题
[解决办法]
应该让这个类Loan实现Serializable接口,报错的原因是因为你没有实现.
[解决办法]
使用ObjectOutputStream的writeObject方法时这个对象必须是实现Serializable接口