传对象
Student
package day41; public class Student { int math; int chinese; int english; public Student(int math, int chinese, int english) { this.chinese = chinese; this.math = math; this.english = english; } }
StudentCalc
package day41; public class StudentCalc { double avg(Student student) { int chineseScore = student.chinese; int englishScore = student.english; int mathScore = student.math; int sum = student.chinese + student.math + student.english; return sum / 3; } }
StudentTest
package day41; public class StudentTest { public static void main(String[] args) { // 生成一个学生 Student student = new Student(60, 70, 80); // 生成一个计算学生成绩的对象 StudentCalc calc = new StudentCalc(); double avg = calc.avg(student); System.out.println(avg); } }
========================================================================================================================
Student
package day42; public class Student { int height; public Student() { } public Student(int height) { this.height = height; } }
StudentCalc
package day42; public class StudentCalc { public double avg(Student[] students) { int sum = 0; for (int i = 0; i < students.length; i++) { sum += students[i].height; } return sum / 5; } }
StudentTest
package day42; import java.util.Scanner; public class StudentTest { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Student[] student = new Student[5]; for (int i = 0; i < 5; i++) { System.out.println("请输入第" + (i + 1) + "个学生身高:"); int height1 = scanner.nextInt(); student[i] = new Student(); student[i].height = height1; } StudentCalc calc = new StudentCalc(); double avg = calc.avg(student); System.out.println(avg); } }