正确打印到文件,但随后挂起

时间:2013-11-26 16:57:54

标签: java loops printing output switching

我将程序设置为打印到文件,该文件正常工作。唯一的问题是,由于我进行了此更改,因此在将数据加到文件后,程序不会继续运行。

Loan.printAmortTable(name, custID, loanID, cBalance, term, cPayment);
System.out.println();
System.out.print("Would you like to print this schedule? y/n: ");
String l = input.next();
switch(l)
{
case "y": 
    try 
    {
         Loan.printSchedule(name, custID, loanID, cBalance, term, cPayment);
    } 
    catch (FileNotFoundException e) 
        {
         e.printStackTrace();
    }
    System.out.println("Printed to output.txt");
    input.next();
    break;
case "n":
    break;
}

Loan.printSchedule

public static void printSchedule(String name, int custID, int loanID, double loanAmount, int term, double payment) throws FileNotFoundException
{
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
out.println("Name " + name);
out.println("ID # " + custID);
out.println("Loan # " + loanID);
out.println("Amount Borrowed " + loanAmount);
out.println("Interest Rate 10.99%");
out.println("Term of the loan " + term);
out.println();

out.println("Payment     Payment     Interest     Principle     Outstanding");
out.println("Number      Amount      Portion      Portion       Balance  ");
double pay = Loan.amortization(loanAmount, term);
double balance = loanAmount;
int i = 0;
while (i<term*12)
{
out.printf("%3d", i + 1);
out.printf("%14.2f",pay);
double interest = balance * (interestRate);
interest = (double)Math.round(interest*100)/100;
out.printf("%11.2f", interest);
double principal = payment - interest;
principal = (double)Math.round(principal*100)/100;
out.printf("%15.2f", principal);
balance = balance - principal;   
    balance = (double) Math.round(balance*100)/100;
    out.printf("%15.2f%n", balance);
    i++;
}
out.close();
}

这是某种缓冲问题吗?

1 个答案:

答案 0 :(得分:2)

您已在此处切换System.out

System.setOut(out);

然后,关闭该流。从该方法返回后,您尝试再次打印到System.out,这是失败的。删除System.setOut(out);行,它应该可以正常工作。