補足説明
以前のプログラム(Error2.java)ではSumupStudent→Error2
で作っていましたがSumupStudentのままでも問題なく動くので今回は変更しないで作成しました。
注意
このプログラムをコンパイルするときには
javac Error2.java
プログラムを動かす時には
java SumupStudent
となるので注意してください。
class Student {
//インスタンス変数の宣言
private String name; //名前
private int[] result = new int[3]; //テストの点数格納配列(数学、化学、物理)
private float total=0; //合計点
private float ave=0; //平均点
//コンストラクタ(Java絵本P74)
public Student(String who, int math, int chemistry, int physics){
//インスタンス変数への値の代入
name = who;
result[0] = math;
result[1] = chemistry;
result[2] = physics;
}
//学生の名前の取得
public String getName(){
return name;
}
//各科目の点数の取得
public int getResult(int num){
return result[num];
}
//合計点の取得
public float getTotal(){
//合計点の初期化
total = 0;
for(int i=0; i<result.length; i++){
total = total + result[i];
}
return total;
}
//平均点の取得
public float getAve(){
ave = 0;
if(total!=0){
ave=total/result.length;
}
return ave;
}
}
class SumupStudent{
public static void main(String args[]){
//Studentクラスのインスタンス生成
Student sato = new Student("佐藤",77,65,80); //佐藤オブジェクト
Student suzuki = new Student("鈴木",88,59,90);//鈴木オブジェクト
Student tanaka = new Student("田中",64,85,54);//田中オブジェクト
//学生テストデータの出力
//佐藤さんのデータ;
System.out.println(sato.getName()+ "さんのテスト結果");
System.out.print("数学:" + sato.getResult(0) + "点 ");
System.out.print("化学:" + sato.getResult(1) + "点 ");
System.out.println("物理:" + sato.getResult(2) + "点 ");
System.out.println("合計:" + sato.getTotal()+ "点 ");
System.out.println("平均:" + sato.getAve()+ "点 ");
System.out.println(tanaka.getName()+ "さんのテスト結果");
System.out.print("数学:" + tanaka.getResult(0) + "点 ");
System.out.print("化学:" + tanaka.getResult(1) + "点 ");
System.out.println("物理:" + tanaka.getResult(2) + "点 ");
System.out.println("合計:" + tanaka.getTotal()+ "点 ");
System.out.println("平均:" + tanaka.getAve()+ "点 ");
}
}
最終更新:2009年12月11日 17:08