集册 Java实例教程 存储学生姓名和平均成绩的学生班级。

存储学生姓名和平均成绩的学生班级。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

706
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
创建和测试学生对象。


public class Main
/**
 from
* NowJava.com 
**/

{

   public static void main(String[] args)

   {

      Student account1 = new Student("James Bond", 93.5);

      Student account2 = new Student("Michael Bates", 72.75); 


      System.out.printf("%s's letter grade is: %s%n", 

         account1.getName(), account1.getLetterGrade());      

      System.out.printf("%s's letter grade is: %s%n", 

         account2.getName(), account2.getLetterGrade());      

   } 

}

class Student 

{

   private String name; 

   private double average; // from N o w  J a v a  .   c o m


   // constructor initializes instance variables

   public Student(String name, double average)

   {

      this.name = name;


      // validate that average is > 0.0 and <= 100.0; otherwise,

      // keep instance variable average's default value (0.0)

      if (average > 0.0) {

         if (average <= 100.0){

            this.average = average; // assign to instance variable

         }

      }

   }


   // sets the Student's name

   public void setName(String name)

   {

      this.name = name; 

   }


   // retrieves the Student's name

   public String getName()

   {

      return name;

   }


   // sets the Student's average

   public void setAverage(double average)

   {

      // validate that average is > 0.0 and <= 100.0; otherwise,

      // keep instance variable average's current value  

      if (average > 0.0) {

         if (average <= 100.0){

            this.average = average; // assign to instance variable

         }

      }

   }


   // retrieves the Student's average

   public double getAverage()

   {

      return average;

   }


   // determines and returns the Student's letter grade

   public String getLetterGrade()

   {

      String letterGrade = ""; // initialized to empty String


      if (average >= 90.0)

         letterGrade = 
展开阅读全文