mardi 29 août 2017

Random selection from array list

I want to select a student randomly for messfood(). Trying to print the student name there.Each week, any of the student should be selected for mess food charge. Tried with String random = list.get(new Random().nextInt(list.size()));. But is shows error. Help me with this.

public class Student {
int rollNo, yearOfStudy;
String fName, lName, activity;

Student(int rollNo, String fName, String lName, int yearOfStudy) {
    this.rollNo = rollNo;
    this.fName = fName;
    this.lName = lName;
    this.yearOfStudy = yearOfStudy;
}
public void display(){
    System.out.println("Roll Number: "+rollNo +"\nName: "+fName+ " "+lName + "\nYear Of Study: "+yearOfStudy+"\n\n");

}
public void messFood(){
    System.out.println("week 1, Mess food Incharge: ");

}

}

class Collection {
public static void main(String[] args) {
    Student s1 = new Student(1, "Alex", "Iwobi", 2013);
    Student s2 = new Student(2, "Denis", "Suarez", 2013);
    Student s3 = new Student(3, "Gerard", "Deulofeu", 2013);
    Student s4 = new Student(4, "Petr", "Cech", 2013);



    List studentList = new ArrayList();
    studentList.add(s1);
    studentList.add(s2);
    studentList.add(s3);
    studentList.add(s4);


    Iterator it = studentList.iterator();
    while(it.hasNext()){
        Student s=(Student)it.next();
        s.display();

    }
}

}




Aucun commentaire:

Enregistrer un commentaire