Java多for循环值打印方法及复利计算器结果展示技术问询
Java相关问题解答
问题1:如何在Java中打印多个for循环中的值?
其实要看你的具体需求是打印每个循环各自的元素,还是把多个循环的元素组合起来输出。我分两种最常见的场景给你举实例:
场景1:多个独立for循环,分别输出内容
这种情况很直接,在每个循环内部加入打印语句即可,比如遍历两个不同的数组:
public class PrintLoopValues { public static void main(String[] args) { // 第一个循环:遍历数字数组 int[] numbers = {1, 2, 3, 4}; System.out.println("第一个循环的元素:"); for (int num : numbers) { System.out.println(num); } // 第二个循环:遍历字符串数组 String[] fruits = {"Apple", "Banana", "Orange"}; System.out.println("\n第二个循环的元素:"); for (String fruit : fruits) { System.out.println(fruit); } } }
场景2:嵌套for循环,打印组合值
如果是嵌套循环(比如处理行和列的结构),可以在内部循环里打印每组组合,或者按行整理输出:
public class NestedLoopPrint { public static void main(String[] args) { // 外层循环控制行数,内层控制列数 for (int i = 1; i <= 3; i++) { System.out.print("第" + i + "行:"); for (int j = 1; j <= 3; j++) { // 打印每行的列元素,用空格分隔 System.out.print(i + "-" + j + " "); } // 每行结束后换行 System.out.println(); } } }
运行后输出:
第1行:1-1 1-2 1-3 第2行:2-1 2-2 2-3 第3行:3-1 3-2 3-3
如果你的场景和上面不同,可以补充具体需求,我再帮你调整方案。
问题2:开发1000美元本金、15年期的复利计算器
先明确复利的核心逻辑:如果是每年复利一次,公式简化为 当年本息 = 上一年本息 × (1 + 年利率)。你提到的嵌套循环其实不是必须的——基础计算用单个循环就足够,嵌套循环适合对比多种利率/复利频率的场景,我先给你基础版本,再扩展嵌套循环的用法。
基础版本:固定年利率,逐年展示结果
假设年利率为5%(可自行调整),代码如下:
public class CompoundInterestCalculator { public static void main(String[] args) { double principal = 1000; // 初始本金 int years = 15; // 投资期限 double annualRate = 0.05; // 年利率5% System.out.println("复利计算结果(年利率" + (annualRate * 100) + "%):"); System.out.printf("%-5s %-15s %-15s\n", "年份", "年末本金", "当年收益"); double currentAmount = principal; for (int year = 1; year <= years; year++) { double annualEarnings = currentAmount * annualRate; currentAmount += annualEarnings; // 格式化输出,保留两位小数 System.out.printf("%-5d $%-14.2f $%-14.2f\n", year, currentAmount, annualEarnings); } // 展示最终总收益 double totalEarnings = currentAmount - principal; System.out.printf("\n15年后总本息:$%.2f,总收益:$%.2f\n", currentAmount, totalEarnings); } }
运行后会逐年输出每一年的本金和收益,最后给出汇总结果,清晰直观。
扩展版本:嵌套循环对比多种年利率
如果想同时对比不同年利率(比如3%、5%、7%)的收益情况,这时候就需要嵌套循环:外层循环遍历不同利率,内层循环计算每年的本息:
public class CompoundInterestComparison { public static void main(String[] args) { double principal = 1000; int years = 15; double[] rates = {0.03, 0.05, 0.07}; // 三种对比利率 for (double rate : rates) { double currentAmount = principal; System.out.println("\n=== 年利率" + (rate * 100) + "% ==="); System.out.printf("%-5s %-15s\n", "年份", "年末本金"); for (int year = 1; year <= years; year++) { currentAmount *= (1 + rate); System.out.printf("%-5d $%-14.2f\n", year, currentAmount); } double totalEarnings = currentAmount - principal; System.out.printf("总收益:$%.2f\n", totalEarnings); } } }
这个版本会分别输出三种利率下的逐年结果,方便你直观对比不同利率对收益的影响,这就是嵌套循环在这个场景下的实际应用。
内容的提问来源于stack exchange,提问作者Sam Davis
相关产品推荐
相关产品推荐

