循环语句

while语句

基本格式

while(条件){
     
    循环代码块
}System.out.println("");

int i = 1;
while (i<=50){
     
   System.out.println("第"+i+"份试卷");
   i++;
}

do-while语句

基本格式

do{
     
    执行的代码块
}while(条件句);

Scanner s = new Scanner(System.in);
boolean isPassed = true;
do {
     
    System.out.println("账号上机测试");
    System.out.println("老师检查是否合格(合格是false 不合格是true)");
    isPassed = s.nextBoolean();
}while (isPassed);

while和do-while的区别:如果初始条件不匹配,while一次都不执行,do-while会执行一次

for循环语句

基本格式`

for(int i = 0; i< 10; i++){
     
    循环语句
}

//统计5门课成绩,并统计平均分
Scanner s = new Scanner(System.in);
System.out.print("输入学生姓名");
String name = s.next();
int total = 0;
for (int i = 1; i <= 5; i++) {
     
    System.out.print("第"+i+"门课的成绩");
    int num = s.nextInt();
    total += num;
}
System.out.println(name+"平均分为"+total/5.0);

斐波那契数列

int a = 1;
int b = 1;
for (int i = 3; i <= 12; i++) {
     
    if (i%2==1){
     
        a += b;
    }else {
     
        b += a;
    }
}
System.out.println(b);

int a = 1;
int b = 1;
for (int i = 3; i <= 12; i++) {
     
    a += b;
    int temp = a;
    a = b;
    b = temp;
}
System.out.println(b);

你可能感兴趣的:(基础,java)