第四章:循环语句知识点及部分例题

循环语句:在给定条件成立时,反复执行某程序段,直到条件不成立为止。给定的条件称为循环条件***,反复执行的程序段叫做循环体*。
While 适合于循环条件已知 但是循环次数未知的情况 ;
for 适合于循环次数已知的情况 ;
for 和while可以完全互换;

1.while(循环继续条件){
循环体
}
首先,while执行循环条件表达式,它返回一个布尔值(true或者false)。如果条件表达式返回true,则执行大括号中的循环体表达式。然后继续测试条件表达式并执行循环体,直到不满足条件返回false为止。

顺序:循环初始化–循环继续条件–循环体–循环间距
循环初始化
2.do{
循环体;
}while(循环结束条件表达式);
do while 与while的区别在于:语句先执行循环体再进行计算条件表达式,所以do while语句的循环体至少被执行一次。

4.while(true){
循环体
循环间距
if(循环结束条件){
break;
}

5.for(循环初始化;循环继续条件;循环步长){
循环体
}
循环初始化–循环继续条件–循环体–循环间距—

6.跳转语句:break 、continue
break有两种作用:(1)跳出switch结构继续执行后续语句;
(2)用来终止整个循环,程序会跳到循环后面的语句继续执行 ;
continue:用来终止本次循环,即终止本轮循环, 程序会跳过后面的语句,转而执行循环的第一条语句;

6.函数的重载:
在同一类中,如有同名函数,则称之为函数之间为重载。
例题部分
例题1: 统计用户输入的数字中,正负数的个数,总和,以及平均值,输入0时,程序结束。
public static void main(String[] args){
注释://思路:
//1.获取用户输入的数字(输入0时,程序结束)
//2.判断正数负数的个数
//3.计算输入值的和 和平均值
//4输出正负数个数、平均值、总和
Scanner scanner=new Scanner(System.in);
System.out.print(“enter the number,以0结束”);
int Zcount=0; //正数的个数
int Fcount=0;// 负数的个数
int total=0; //数字总和
double average=1;//平均值
while(true){
int number=scanner.nextInt();
if (number>0){
Zcount++;
}else if(number<0){
Fcount++;
}else{
break;
}
total+=number; //总和
}
average=1.0total/(Zcount+Fcount); //平均值 乘以1.0转换为浮点数
System.out.println(“the Zcount is”+Zcount);
System.out.println(“the Fcount is”+Fcount);
System.out.println(“the total is”+total);
System.out.println(“the average is”+average);
}
}
**例题2
for 循环
用户输入学生个数、姓名以及相应成绩,程序能显出前两名的成绩和姓名;
public class Test4_2 {
public static void main(String[] args){
// 获取学生姓名 成绩 个数
String firstName="";
String secondName="";
int firstScore=0;
int secondScore=0;
Scanner scanner= new Scanner(System.in);
System.out.print(“enter the number of the students :”); //提示用户输入学生数量
int count=scanner.nextInt();
for(int i=0;i<count;i++){
System.out.print(“enter students’s name :”); //提示输入姓名
String name=scanner.next(); //////////////////////定义变量接收输入的姓名
System.out.print(“enter students’s score :”); //提示输入成绩
int score=scanner.nextInt();
if(score>firstScore){
secondScore=firstScore; 判断成绩高低,将输入的成绩与第一名相比;
secondName=firstName;
firstScore=score;
firstName=name;
}else{
secondScore=score;
secondName=name;
}
}
System.out.print(“firstscore is :”+ firstName+firstScore);
System.out.print(“secondscore is :”+secondName+secondScore);
}

}

猜你喜欢

转载自blog.csdn.net/zhangpupu320/article/details/82956048
今日推荐