Java-do…while语句的使用
在Java中,循环是迭代执行一段代码的一个重要概念。
Java提供了多种循环语句,其中包括do…while语句。
这篇博客探讨Java中do…while语句的用法,并进行代码示例。
首先,我们来了解一下do…while语句的语法。
它的基本结构是:
do {
// 在循环内执行的代码
} while (条件);
do…while语句与while语句的区别在于:
do…while语句先执行一次循环体中的代码,然后再检查循环条件。这意味着即使条件开始时就不满足,循环体仍会执行至少一次。
接下来,我们通过几个例题来体会do…while语句的用法。
- 示例1:使用do…while语句计算1到10的和。
package com.edu.jsu;
public class DoWhileSum {
public static void main(String[] args) {
int sum = 0;
int i = 1;
do{
sum += i;
i++;
}while(i <= 10);
System.out.println("1到10的和为:" + sum);
}
}
运行结果:
- 示例2:使用do…while循环将输入的数字逆序输出。
package com.edu.jsu;
import java.util.Scanner;
public class DoWhileNiXu {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("输入一个数字:");
int num = scanner.nextInt();
System.out.print("逆序输出为:");
do{
System.out.print(num % 10);
num /= 10;
}while(num > 0);
}
}
运行结果:
- 示例3:使用do…while循环判断用户输入的密码是否正确,如果不正确则重新输入。
package com.edu.jsu;
import java.util.Scanner;
public class DoWhileJudge {
public static void main(String[] args) {
final String password = "112234";
Scanner scanner = new Scanner(System.in);
String input;
do{
System.out.print("请输入密码:");
input = scanner.next();
}while (!input.equals(password));
System.out.println("密码正确!");
}
}
运行结果:
- 示例4:使用do…while循环输出1到10的乘法表。
package com.edu.jsu;
public class DoWhileChengFaBiao {
public static void main(String[] args) {
int i = 1;
do{
int j = 1;
do {
System.out.print(i + "*" + j + "=" + (i * j) + "\t");
j++;
}while (j <= 10);
System.out.println();
i++;
}while (i <= 10);
}
}
运行结果:
- 示例5:使用do…while循环求解斐波那契数列的前20项并输出结果。
package com.edu.jsu;
public class DoWhileFBNQ {
public static void main(String[] args) {
int n = 20;
int a = 0, b = 1;
int i = 1;
System.out.println("斐波那契数列的前20项为:");
do{
System.out.print(a+"\t");
int c = a + b;
a = b;
b = c;
i++;
}while (i <= n);
}
}
运行结果:
END…