for循环:
测试代码1:
package testfor.com;
public class ForSumExample {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("1到100之间的数字和为:" + sum);
}
}
测试代码2:
package testfor.com;
//通过初始化语句 int i = 1 初始化循环变量,条件语句 i <= 5 控制循环的执行次数,更新语句 `i++` 在每次迭代后更新循环变量的值。
public class ForLoopExample {
public static void main(String[] args) {
// 打印 1 到 5 的数字
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
测试代码3:
package testfor.com;
import java.util.Scanner;
//使用for循环遍历学生信息和成绩,并计算平均成绩,使用类封装学生信息。
class Student {
String name;
int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
}
public class TestFor {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Student[] students = new Student[5];
for (int i = 0; i < 5; i++) {
System.out.print("输入学生姓名:");
String name = input.nextLine();
System.out.print("输入学生成绩:");
int score = input.nextInt();
input.nextLine(); // 清空输入缓冲区
students[i] = new Student(name, score);
}
// 显示学生成绩
System.out.println("学生成绩列表:");
for (int i = 0; i < 5; i++) {
System.out.println("学生姓名:" + students[i].name + ",成绩:" + students[i].score);
}
// 计算平均成绩
int totalScore = 0;
for (int i = 0; i < 5; i++) {
totalScore += students[i].score;
}
double averageScore = (double) totalScore / students.length;
System.out.println("平均成绩:" + averageScore);
}
}
运行结果如下:
测试代码4:
package testfor.com;
import java.util.Scanner;
import java.util.ArrayList;
//使用动态数组ArrayList存储学生信息,并且输入学生数量。
//使用for-each循环遍历学生信息和成绩,并计算平均成绩。
public class CalculationGrades {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> students = new ArrayList<>();
System.out.print("输入学生数量:");
int numStudents = input.nextInt();
input.nextLine(); // 清空输入缓冲区
for (int i = 0; i < numStudents; i++) {
System.out.print("输入第 " + (i + 1) + " 个学生的姓名:");
String name = input.nextLine();
System.out.print("输入第 " + (i + 1) + " 个学生的成绩:");
int score = input.nextInt();
input.nextLine(); // 清空输入缓冲区
students.add(new Student(name, score));
}
// 显示学生成绩
System.out.println("学生成绩列表:");
for (Student student : students) {
System.out.println("学生姓名:" + student.name + ",成绩:" + student.score);
}
// 计算平均成绩
int totalScore = 0;
for (Student student : students) {
totalScore += student.score;
}
double averageScore = (double) totalScore / students.size();
System.out.println("平均成绩:" + averageScore);
}
}
运行结果如下: