11. 循环结构-while循环
【摘要】 Java系列第十一课
一、生活中的循环
二、循环具备的特点
三、循环的分类
固定循环:循环的次数知
非固定循环:循环的次数不知道;这个必须有退出条件,否则程序会一直进行下去。
固定循环:for循环
非固定循环:while循环、do-while循环
四、循环语法
1、while循环
语法如下
2、习题1:固定次数循环
第一题代码如下:
public class Demo12 {
public static void main(String[] args) {
int i = 1;
while (i < 5){
System.out.println("好好学习");
i ++;
}
}
}
结果如下:
第二题代码如下:
public class Demo12 {
public static void main(String[] args) {
int i = 1;
while (i < 5){
System.out.println(i);
i ++;
}
}
}
结果如下:
第三题代码如下:
public class Demo12 {
public static void main(String[] args) {
int i = 1;
int sum = 0;
while (i <= 5){
sum += i;
i ++;
}
System.out.println(sum);
}
}
结果如下:
3、习题2
第一题:
代码如下:
public class Demo12 {
public static void main(String[] args) {
int i = 1;
while (i <= 100){
if (i % 2 == 0){
System.out.println(i);
}
i++;
}
}
}
结果如下:
第二题:
代码如下:
public class Demo12 {
public static void main(String[] args) {
int i = 1;
while (i <= 100){
if (i % 2 == 0 && i % 3 == 0){
System.out.println(i);
}
i++;
}
}
}
结果如下:
第三题:
代码如下:
public class Demo12 {
public static void main(String[] args) {
int i = 1;
int j = 0;
while (i <= 100){
if (i % 3 == 0){
j++;
}
i++;
}
System.out.println("1-100之间能被3整除的数的个数为:" + j);
}
}
结果如下:
第四题:
代码如下:
public class Demo12 {
public static void main(String[] args) {
int i = 100;
while (i >= 0){
System.out.print(i + ",");
i -= 5;
}
}
}
结果如下:
第五题:
代码如下:
public class Demo12 {
public static void main(String[] args) {
int i = 5;
int plus = 1;
while (i > 0){
plus *= i;
i--;
}
System.out.println(plus);
}
}
结果如下:
4、习题3(非固定次数循环)
代码如下:
import java.util.Scanner;
public class Demo12 {
public static void main(String[] args) {
Scanner superman = new Scanner(System.in);
int score;
while (true){
System.out.println("请输入学员的成绩:");
score = superman.nextInt();
if (score == -1){
break;
}
}
}
}
下面的代码好一点:
import java.util.Scanner;
public class Demo12 {
public static void main(String[] args) {
Scanner superman = new Scanner(System.in);
int score = 0;
// 直接把条件写到这个里面,节省代码。
while (score != -1){
System.out.print("请输入学员的成绩:");
score = superman.nextInt();
}
}
}
结果如下:
5、习题4
代码如下: // 这里有一个新的知识
import java.util.Scanner;
public class Demo12 {
public static void main(String[] args) {
Scanner superman = new Scanner(System.in);
String name = "a";
while (name.equals("q") == false){
System.out.print("请输入学员的姓名:");
name = superman.next();
}
}
}
结果如下:
6、习题5:这里有一个大坑
代码如下:
import java.util.Scanner;
public class Demo12 {
public static void main(String[] args) {
int xiao_age = 12;
int monther_age = 32;
int count_year = 0;
// 注:这里条件千万不要写成monther_age / xiao_age == 2
// 因为,整数除法得到的结果,本来就是四舍五入
// 可以看到,32/12在java中本来就等于2了。
// 这是一个大坑,注意!!!
while (!(monther_age == 2 * xiao_age)){
xiao_age++;
monther_age++;
count_year++;
}
System.out.println(count_year);
}
}
结果如下:
【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请自行联系原作者进行授权。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)