【问题标题】:Printing to a file properly, but then hangs up正确打印到文件,但随后挂断
【发布时间】:2013-11-26 16:57:53
【问题描述】:

我将程序设置为打印到文件,该文件可以正常工作。唯一的问题是,由于我进行了此更改,因此在将数据输出到文件后,程序无法正常运行。

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();
}

这是某种缓冲问题吗?

【问题讨论】:

  • 您确定while (i&lt;term*12) 循环正在终止吗?
  • 是的,它正在终止。我在一个方法中具有完全相同的循环,该方法将相同的信息打印到屏幕上,并且运行良好。

标签: java loops printing output switching


【解决方案1】:

您已在此处切换System.out

System.setOut(out);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多