do-while

xiaoxiao2021-02-28  14

while循环语句首先检测循环条件,因此,循环体中的代码可能不被执行。如果希望循环体至少被执行一次,则应该将检测条件放在最后。使用do/while循环语句可以实现这种操作方式。它的语法格式为: do statement while(condition)

这种循环语句先执行语句(通常是一个语句块),再检测循环条件;然后重复语句,再检测,以此类推。 程序中,首先计算退休账户中的余额,然后再询问是否打算退休。 程序源代码如下: import java.util.Scanner; public class Do_While { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("请输入您需要的退休金:"); double goal = in.nextDouble(); System.out.print("请输入您每年存储的金额:"); double payment = in.nextDouble(); System.out.print("请输入年利率(%):"); double interestRate = in.nextDouble(); double balance = 0; int years = 0; String input; do { balance += payment; double interest = balance * interestRate / 100; balance += interest; years++; System.out.println(); System.out.printf("%d年以后,您的总金额为%,2f", years, balance); System.out.print("您准备退休吗(N/Y)"); input = in.next(); } while(input.equals("N")); } }

程序运行结果见图1。

图1
转载请注明原文地址: https://www.6miu.com/read-2650017.html

最新回复(0)