編寫Java程序:創(chuàng)建一個名為Student的類,包含姓名、學(xué)號、成績屬性,并且提供計(jì)算平均成績的方法,可以查看所有屬性和屬性值。文章來源:http://www.zghlxwxcb.cn/news/detail-847440.html
package com.edu.jsu;
public class Student {//創(chuàng)建一個類,類名為Student
private String name;//聲明姓名屬性
private int id;//聲明學(xué)號屬性
private int[] scores;//聲明成績屬性
public Student(String name, int id, int[] scores) { //構(gòu)造方法,用于初始化姓名、學(xué)號和成績屬性
this.name = name;
this.id = id;
this.scores = scores;
}
public double averageScore() { //計(jì)算平均成績的方法
int sum = 0; //初始化總分為0
for (int score : scores) {
sum += score;
}
return (double) sum / scores.length; //總分除以科目數(shù)得到平均成績
}
public String getName() { //獲取姓名屬性的方法
return name;
}
public void setName(String name) { //設(shè)置姓名屬性的方法
this.name = name;
}
public int getId() { //獲取學(xué)號屬性的方法
return id;
}
public void setId(int id) { //設(shè)置學(xué)號屬性的方法
this.id = id;
}
public int[] getScores() { //獲取成績屬性的方法
return scores;
}
public void setScores(int[] scores) { //設(shè)置成績屬性的方法
this.scores = scores;
}
public void printDetails() { //查看所有屬性和屬性值的方法
System.out.println("Name: " + name);
System.out.println("ID: " + id);
System.out.println("Scores: ");
for (int i = 0; i < scores.length; i++) {
System.out.println("Subject " + (i + 1) + ": " + scores[i]);
}
}
public static void main(String[] args) { //測試 Student 類的主方法
Student student1 = new Student("李華", 202301, new int[]{88, 90, 78, 92, 95});//創(chuàng)建一個名為李華的學(xué)生對象
double averageScore = student1.averageScore(); //調(diào)用計(jì)算平均成績的方法
System.out.println(student1.getName() + "同學(xué)的平均成績?yōu)椋? + averageScore);
student1.printDetails();//調(diào)用查看所有屬性和屬性值的方法
}
}
運(yùn)行結(jié)果:文章來源地址http://www.zghlxwxcb.cn/news/detail-847440.html
到了這里,關(guān)于Java-創(chuàng)建一個名為Student的類,包含姓名、學(xué)號、成績屬性,并且提供計(jì)算平均成績的方法,可以查看所有屬性和屬性值。的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!