注意
- 外層控制行數(shù)
- 內(nèi)層控制列數(shù)
定義
- 一個循環(huán)體內(nèi)又包含另一個完整的循環(huán)結(jié)構(gòu)
- 外層循環(huán)變量變化一次秋秤,內(nèi)層循環(huán)變量就要變化一次
練習題
-
若有3個班級各4名學員參賽拖刃,如何計算每個班級參賽學員的平均分址貌?
--分析:
1.外層循環(huán)控制班級數(shù)目
2.內(nèi)層循環(huán)控制每個班級學員數(shù)目
public class linshi {
public static void main(String[] args) {
for (int j = 0;j < 3;j++)
{
int sum =0;
System.out.println("請輸入第" + (j + 1) + "個班級的成績");
for (int i = 0;i< 4;i++)
{
System.out.println("第" + (i + 1) + "個學員的成績:");
Scanner scanner = new Scanner(System.in);
int grade = scanner.nextInt();
sum =sum + grade;
}
System.out.println("第" + (j + 1) + "班級參賽學員的平均分是:" + sum/4);
}
}
}
-
用#打印矩形圖案
--分析:
1.外層循環(huán)控制行數(shù)
2.內(nèi)層循環(huán)控制每行的#號數(shù)
public class linshi {
public static void main(String[] args) {
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < 4; i++)
{
System.out.print("#\t");
}
System.out.println("");
}
}
}
-
用#打印倒直角三角形圖案
public class linshi {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入直角三角形的行數(shù):");
int hangshu = scanner.nextInt();
for (int j = hangshu; j > 0; j--)//控制的是打印多少行
{
for (int i = 0; i < j; i++)//控制的是每行打印多少列
{
System.out.print("*\t");
}
System.out.println();
}
}
}
- 用#打印正直角三角形圖案
//請輸入直角三角形的行數(shù):5
//#
//# #
//# # #
//# # # #
//# # # # #
public class linshi {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入直角三角形的行數(shù):");
int hangshu = scanner.nextInt();
for (int j = 0;j < hangshu;j++)//控制的是打印多少行
{
for (int i = 0; i < j + 1;i++)//控制的是每行打印多少列
{
System.out.print("*\t");
}
System.out.println();
}
}
}
-
1,3,5,7,9
public class linshi {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入直角三角形的行數(shù):");
int hangshu = scanner.nextInt();
for (int j = 0;j < hangshu ;j++)//控制的是打印多少行
{
for (int i = 0; i < 2*j + 1;i++)//控制的是每行打印多少列
{
System.out.print("*\t");
}
System.out.println();
}
}
}
-
打印九九乘法表
public class linshi {
public static void main(String[] args) {
for (int j = 0;j < 9;j++)//控制的是打印多少行
{
for (int i = 0; i < j + 1;i++)//控制的是每行打印多少列
{
System.out.print((i + 1) + "*" + (j + 1) + "=" + ((i + 1)*(j + 1)) + "\t");
}
System.out.println();
}
}
}
在二重循環(huán)中使用continue
-
若有3個班級各4名學員參賽盛龄,計算每個班級參賽學員平均分,統(tǒng)計成績大于85分學員數(shù)
public class linshi {
public static void main(String[] args) {
int count = 0;
for (int j = 0;j < 3;j++)
{
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入第" + (j + 1) + "個班級的成績");
int sum = 0;
int grade = 0;
for (int i = 0;i < 4;i++)
{
System.out.println("第" + (i + 1) + "個學員的成績:");
grade = scanner.nextInt();
sum += grade;
if (grade <= 85)
{
continue;
}
else
{
count++;
}
}
System.out.println("第" + (j + 1) + "班級參賽學員的平均分是" + sum/4);
}
System.out.println("成績85分以上的學員人數(shù)有" + count + "人");
}
}