gpt4 book ai didi

Java:如何在一定次数的迭代后暂停输出直到按下一个键

转载 作者:行者123 更新时间:2023-11-30 09:30:08 25 4
gpt4 key购买 nike

我正在为我的一门大学类(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com