for 循环和 while循环 其实执行理念是相同的。
先初始化变量,然后再判断条件,成立则执行循环体中的代码,然后执行增量,再次判定,判定条件为false则跳过循环结构执行下面的语句,
for循环语句如下:
for(初始化变量;循环条件;增量){
循环体语句..
}
for循环 三个表达式都可以省略不写,但是分号不能不写 两个分号不能漏掉,这会一直循环执行
public class Test{
public static void main(String args[]){
for(int a=0;a<=10;a++){
System.out.println(a);
}
}
/*执行顺序为: 1、执行初始化变量
2、判定循环条件如果成立执行3否则执行6
3、执行循环体语句
4、执行增量
5、重新判定循环条件,如果成立则继续执行3,否则执行6
6、退出for循环结构 */
例题:for循环和while循环的比对,输入十名玩家的成绩,求出十名玩家的总和以及平均值。
import java.util.Scanner;
public class Test_026 { //for
public static void main(String[] args) {
int sums = 0;
int avg = 0;
System.out.println("请输入十名玩家的成绩");
for (int a = 1; a <= 10; a++) {
Scanner s = new Scanner(System.in);
int scores = s.nextInt();
System.out.println("第" + a + "名玩家的成绩已经采集,请继续输入第" + (a + 1) + "玩家的成绩");
sums += scores; // 总和,叠加传递进来的十名学生的成绩.
}
avg = sums / 10;
System.out.println("十名玩家的总成绩为" + sums);
System.out.println("十名玩家的平均成绩为" + avg);
}
}
public class Test_026{ //while
public static void main(String []args) {
System.out.println("请输入十名玩家的成绩");
Scanner s =new Scanner(System.in);
int sums =0; int avg =0;
int a=1;
while(a<=10) {
int scores=s.nextInt();
System.out.println("第" + a + "名玩家的成绩已经采集,请继续输入第" + (a + 1) + "玩家的成绩");
sums+=scores;
a++;
}
avg = sums / 10;
System.out.println("十名玩家的总成绩为" + sums);
System.out.println("十名玩家的平均成绩为" + avg);
}
}
public class Test_026 {
public static void main(String[] args) {
/*
* 使用for 循环和while循环 输出下 0+输入数字=9 0+输入数字-1=输入数字-1; 0+输入数字-2=输入数字-2;
* 0+输入数字-3=输入数字-3; 0+输入数字-4=输入数字-4; 0+输入数字-5=输入数字-5; 0*输入数字-6=输入数字-6;
* 0*输入数字-7=输入数字-7; 0*输入数字-8=输入数字-8; 0*输入数字-9=输入数字-9; ...
*/
/*
* System.out.println("请输入一个数"); Scanner s= new Scanner(System.in); int input =
* s.nextInt(); for(int a=0 ,b=input;a<=input;a++,b-- ) {
* System.out.println(a+"+"+b+"="+(a+b));
*
* }
*
* }
*/
// while循环
System.out.println("请输入一个数字");
Scanner s = new Scanner(System.in);
int input = s.nextInt();
int a = 0;
int b = input;
while (a <= input) {
System.out.println(a + "+" + b + "=" + (a + b));
a++;
b--;
}
}
}