作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在为我的一门大学类(class)学习 Java,我需要知道如何在 for 循环的每 12 次迭代后暂停我的程序的输出。我有一个迭代 360 次的循环,我希望每 12 个项目循环输出输出停止,直到按下一个键。我进行了相当多的搜索,但我发现的所有内容都在更高级的上下文中,我不太了解代码中还发生了什么。该程序没有 GUI,它非常简单,我可以将所有代码粘贴到这里:
public class MyMain
{
static double principal = 200000.00;
static double interest = .0575;
static int term = 360;
static DecimalFormat currency = new DecimalFormat("###,###.##");
public static void main(String[] args)
{
MortgageCalculator mortgageWeek2 = new MortgageCalculator(principal, interest, term);
double monthlyPayment = mortgageWeek2.calculate();
System.out.println("Welcome to my Mortgage Calculator.");
System.out.println("The principal on this loan is $" + currency.format(principal) + ".");
System.out.println("The interest on this loan is " + (interest * 100) + "%.");
System.out.println("The term on this loan is " + term + " months (" + term / 12 + " years).");
System.out.println("Payments on this loan will be $" + currency.format(monthlyPayment));
double balanceRemaining = 200000.0;
for (int i = 0; i < 30 * 12; i++)
{
double interestPaid = balanceRemaining * .0575 / 12;
double principalPaid = monthlyPayment - interestPaid;
balanceRemaining = balanceRemaining - principalPaid;
System.out.println("Month " + (i + 1) + " \tPayment Amount: $" + currency.format(monthlyPayment) +
"\tInterest Paid: $" + currency.format(interestPaid) +
" \tPrincipal Paid: $" + currency.format(principalPaid) +
" \tBalance Remaining: $" + currency.format(balanceRemaining));
}
}
}
最佳答案
将 for
循环分成两段,并在外层循环中添加一个 input
语句,如下所示:
Scanner input = new Scanner(System.in);
String userInput = null;
for (int i = 0; i < 30; i++)
{
for (int j = 0; j < 12; j++)
{
double interestPaid = balanceRemaining * .0575 / 12;
double principalPaid = monthlyPayment - interestPaid;
balanceRemaining = balanceRemaining - principalPaid;
System.out.println("Month " + (i*12+j + 1) +
" \tPayment Amount: $" + currency.format(monthlyPayment) +
"\tInterest Paid: $" + currency.format(interestPaid) +
" \tPrincipal Paid: $" + currency.format(principalPaid) +
" \tBalance Remaining: $" + currency.format(balanceRemaining));
}
userInput = input.nextLine();
}
input.close();
停止后,您需要按任意字符和返回键或只按返回键。
关于Java:如何在一定次数的迭代后暂停输出直到按下一个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13391618/
我是一名优秀的程序员,十分优秀!