dowhile和while的代码举例
一、do-while循环示例:
1. 通过do-while循环计算1到100的和:
```
int i = 1;
int sum = 0;
do {
sum += i;
i++;
} while (i <= 100);
System.out.println("1到100的和为:" + sum);
```
2. 通过do-while循环实现猜数字游戏:
```
int secretNumber = 42;
int guess;
do {
System.out.print("猜一个数字:");
guess = Int();
if (guess < secretNumber) {
System.out.println("太小了!");
} else if (guess > secretNumber) {
System.out.println("太大了!");
}
} while (guess != secretNumber);
System.out.println("恭喜你猜对了!");
```
3. 通过do-while循环实现密码输入验证:
```
String password = "123456";do while语句怎么用
String input;
do {
System.out.print("请输入密码:");
input = Line();
} while (!input.equals(password));
System.out.println("密码正确!");
```
4. 通过do-while循环计算斐波那契数列前n项和:
```
int n = 10;
int a = 0, b = 1;
int sum = 0;
int i = 0;
do {
sum += a;
int temp = a;
a = b;
b = temp + b;
i++;
} while (i < n);
System.out.println("斐波那契数列前" + n + "项和为:" + sum);
```
5. 通过do-while循环实现菜单选择功能:
```
int choice;
do {
System.out.println("1. 新建文件");
System.out.println("2. 打开文件");
System.out.println("3. 保存文件");
System.out.println("4. 退出");
System.out.print("请选择操作:");
choice = Int();
switch (choice) {
case 1:
System.out.println("新建文件");
break;
case 2:
System.out.println("打开文件");
break;
case 3:
System.out.println("保存文件");
break;
case 4:
System.out.println("退出");
break;
default:
System.out.println("无效的选择");
break;
}
} while (choice != 4);
```
二、while循环示例:
1. 通过while循环打印1到10的数字:
```
int i = 1;
while (i <= 10) {
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论