java基础起步四-循环结构

网友投稿 594 2022-05-28

文章目录

循环结构介绍:

一、循环结构

1、while循环

2. do-while循环结构

3. for循环

二: 循环结构练习题

1. 从键盘分别输入年月日,使用for+if实现判断这一天是当年的第几天.

2. Java猜数字游戏(数据范围在1-100之间)

3. 使用循环对计算从1加到100的和

方案一: while方案

方案二: do -while 循环

方案三 for循环

循环结构介绍:

一、循环结构

语法:

while(循环条件){

循环操作

}

语法:

do{

循环操作

}while(循环条件);

语法:

for(表达式1;表达式2;表达式3){

//循环体

}

1.表达式1就是一个赋值的语句,循环结构的初始化部分,为循环变量赋初始值 例如:int i=0;

2.表达式2条件语句,循环结构的循环条件,例如:i<100

3.表达式3赋值语句,通常使用++或–运算符。循环结构的迭代部分,通常用来修改循环变量的值 例如:i++

二: 循环结构练习题

class Days{ public static void main(String[] args ){ //从键盘输入年月日 java.util.Scanner input = new java.util.Scanner(System.in); System.out.println("请输入你要查询的年份: "); int year = input.nextInt(); System.out.println("请输入你要查询的月份:"); int mouth = input.nextInt(); System.out.println("请输入你要查询日: "); int day = input.nextInt(); // 定义days累加了第mouth月的day 天 int days = day; for(int i=1; i

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

class GuessNum{ public static void main(String[] args){ java.util.Scanner sc = new java.util.Scanner(System.in); System.out.println("请输入你猜测的数字"); //生成随机数 int guessNum = (int) (Math.random()*100 + 1); while(true){ int result = sc.nextInt(); if ( result < guessNum){ System.out.println("你猜测的数字小了"); }else if(result > guessNum){ System.out.println("你猜测的数字大了"); }else{ System.out.println("恭喜猜对了"); System.out.println("继续玩请输入Y,否则输入N"); String input = sc.next(); if(input.equals("N")){ System.out.println("欢迎下次再来"); break; //equals() 方法比较字符串是否相等 }else if(input.equals("Y")){ System.out.println("正在为你接入新一轮游戏"); System.out.println("请输入你要猜测的数字"); }else{ System.out.println("你的输入有误,游戏正在退出"); break; } } } } }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

public class Sum_while{ public static void main(String[] args){ int sum = 0; int i = 1; while(i<=100){ sum += i; i++; } System.out.println("100内的整数的和是" +sum); } }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

public class Sum_while{ public static void main(String[] args){ int sum = 0; int i = 1; do{ sum += i; i++; }while(i <=100); System.out.println("100内的整数的和是" +sum); } }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

public class Sum_for{ public static void main(String[] args){ int sum = 0; for(int i =1; i<=100;i++){ sum+=i; } System.out.println("100以内的整数和是" +sum); } }

1

2

3

4

5

6

7

java基础起步四-循环结构

8

9

10

11

12

13

14

15

Java

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:熊猫烧香应急处理方法
下一篇:DAS之 数据库自动化运维功能展播5:实时分析
相关文章