วันจันทร์ที่ 16 พฤศจิกายน พ.ศ. 2558

Lab 8 - (Java) Display student records, sorted by age, use insertion sort

public class Student {

  private String name;
  private int weight;
  private int high;
  private int age;
  private int ID;

  public  Student(String name , int weight , int high , int age , int ID ) {
   
   this.name = name ;
   this.weight = weight;
   this.high = high;
   this.age = age;
   this.ID = ID;
   }

  public String get_name(){
    return this.name;
  }
  public int get_weight(){
    return this.weight;
  }
  public int get_high(){
    return this.high;
  }
  public int get_age(){
    return this.age;
  }
  public int get_ID(){
    return this.ID;
  }
  public void set_name(String value){
    this.name = value;
  }
  public void set_weight(int  value){
    this.weight =  value;
  }
  public void set_high(int  value){
    this.high = value;
  }
  public void set_age(int  value){
    this.age =  value;
  }
  public void set_ID(int  value){
    this.ID = value;
  }

  public void display() {

    System.out.println( "NAME: "+this.name);
    System.out.println( "WEIGHT:"+this.weight+"  kg.");
    System.out.println( "HIGH:"+this.high+"  cm.");
    System.out.println( "AGE :"+this.age+"  years old");
    System.out.println( "ID :"+this.ID);

 }
  public static void main(String[] args) {
    Student[] std = {new Student("Park",40,160,18,1),
                    new Student("Nani",50,180,19,2),
                     new Student("Pepe",80,185,20,3),
                     new Student("Giggs",70,160,18,4),
                     new Student("Laws",85,155,18,5)};
    sort_age(std);
    int index = 0;
 
    while(index<std.length){
      std[index].display();
      index = index + 1;
    }
 
  }
   public static void sort_age(Student[] std){
    int index  = 1 ;
    while(index<std.length){
      String value_name = std[index].get_name();
      int value_weight = std[index].get_weight();
      int value_high = std[index].get_high();
      int value_age = std[index].get_age();
      int value_ID = std[index].get_ID();
      int pos = index ;
      while(pos>0 &&std[pos - 1].get_age()>value_age){
         std[pos].set_name(std[pos - 1].get_name());
         std[pos].set_weight(std[pos - 1].get_weight());
         std[pos].set_high(std[pos - 1].get_high());
         std[pos].set_age(std[pos - 1].get_age());
         std[pos].set_ID(std[pos - 1].get_ID());
         pos = pos - 1;
      }
      if(pos != index){
         std[pos].set_name(value_name);
         std[pos].set_weight(value_weight);
         std[pos].set_high(value_high);
         std[pos].set_age(value_age);
         std[pos].set_ID(value_ID);
      }
     index = index + 1;
    }
   
   }
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น