package com.course;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
/**
* given a number, auto-generated all the student ID, which contains 3 digits and is unique
* for each ID generating, customer should enter a student name
* 1. implement sorting all the student record by their ID with comparable interface
* 2. implement sorting all the student record by their name with comparator interface
* @author richard
*
*/
public class ListSortStudent {
List<Student> stuList = new ArrayList<Student>();
final String digitChar = "0123456789";
//generate single student ID with 3 digits
public String genOneID(){
StringBuffer sb = new StringBuffer();
Random ran = new Random();
for(int j=0;j<3;j++){
sb.append(digitChar.charAt(ran.nextInt(digitChar.length())));
}
return sb.toString();
}
/**
* generate a student list which contain auto-generated ID and keyboard input name
* the ID should be unique
*/
public void genStuList(){
Scanner input = new Scanner(System.in);
Scanner input1= new Scanner(System.in);
System.out.print("Please enter the number of student: ");
int stuNum = input.nextInt();
String stuID,stuName;
List<String> idList = new ArrayList<String>();
Student newStu;
for (int i=0;i<stuNum;i++){
stuID = genOneID();
while(idList.contains(stuID)){
stuID = genOneID();
}
idList.add(stuID);
System.out.println("the auto-generated ID is: "+idList.get(i));
System.out.print("Please enter the student name: ");
stuName = input1.nextLine();
newStu = new Student(stuName,stuID);
stuList.add(newStu);
}
}
public void displayStuList(){
for(Student s:stuList){
System.out.println(s.getID()+" "+s.getName());
}
}
public void sortStudentComparable(){
Collections.sort(stuList);
}
public void srotStudentComparator(){
Collections.sort(stuList,new StuComparator());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ListSortStudent lst = new ListSortStudent();
lst.genStuList();
System.out.println("************before sorting********");
lst.displayStuList();
System.out.println("************after sorting by id**********");
lst.sortStudentComparable();
lst.displayStuList();
System.out.println("************after sorting by name**********");
lst.srotStudentComparator();
lst.displayStuList();
}
}