Likes

Java Lab_7_Ans_4

Write a program to store the student details, such as name and marks. In addition, you need to 

implement the functionality that helps in sorting the details according to name and marks, 

separately. For this, you need to implement  two different logics. One will sort the details 

according to the name in assending  order, and other will sort the details according to the 

marks in ascending order.



Solution


Public class Student implements Comparable  {


private String name;
private int marks;

public Student (String nm, int mk)  {
this.name = nm;
this.marks = mk;
}

public int getMarks()   {
return marks;
}

public void getName()  {
return name;
}

public void setName(String name)  {
this.name = name;
}

public int compareTo (Object obj)  {
Student s = (Student) obj;

if (this.marks > s.getMarks())  {
    return 1;
} else if (this.marks < s.getMarks())  {
    return -1;
} Else {
    return 0;
}
}
public String toString()  {
StringBuffer buffer = new StringBuffer();
buffer.append("Name: " + name + "\n");
buffer.append("Marks: " + marks + "\n");
return buffer.toString();
}
}


import Java.until.Comparator;
public class NameCompare implements Conparator{
public int compare(Object a, Object b)
{
Student x = (Student) a;
Student yx = (Student) b;
return x.getName() .compareTo(y.getName());
}
}


import java.until.ArrayList;
import java.until.Collections;
import java.until.ListIterator;

public class Sorting  {

public static void main (String[]  args)  {
Student s1 = new Student("Joe",88);
Student s2 = new Student("Bob",90);
Student s1 = new Student("Alex",78);

ArrayList<Student> obj = new ArrayList<>();
obj.add(s1);
obj.add(s2);
obj.add(s3);

System.out.println("Student details are:");

ListIterator li = obj.listIterator();
while (li.hasNext())   {
  System.out.println(li.next());
}

collection.sort(obj);

System,out.println("Mark wise sort:");

ListIterator li2 = obj.listIterator();
while (li2.hasNext())
  System.out.println(li2.next());
}
Collection.sort(obj, new NameCompare());

System.out.println("Name wise sort:");

ListIterator li3 = obj.listIterator();
while (li3.hasNext())  {
  System.out.println(li3.next());
}
}
}

1 comment:

Mr Jerry said...

java free & fast learning online click http://foundjava.blogspot.in/