Sort ArrayList in Java - java

class Student {
int rollno;
String name, address;
// Constructor
public Student(int rollno, String name, String address) {
this.rollno = rollno;
this.name = name;
this.address = address;
}
// Used to print student details in main()
public String toString() {
return this.rollno + " " + this.name +
" " + this.address;
}
}
class tools {
class Sortbyroll implements Comparator<Student>{
// Used for sorting in ascending order of
// roll number
public int compare(Student a, Student b) {
return a.rollno - b.rollno;
}
}
public ArrayList<Student> sort(ArrayList<Student> arr){
Collections.sort(arr, new Sortbyroll());
return arr;
}
}
class Main
{
public static void main (String[] args) {
ArrayList<Student> ar = new ArrayList<Student>();
ar.add(new Student(111, "bbbb", "london"));
ar.add(new Student(131, "aaaa", "nyc"));
ar.add(new Student(121, "cccc", "jaipur"));
System.out.println("Unsorted");
for (int i=0; i<ar.size(); i++)
System.out.println(ar.get(i));
ar = tools.sort(ar);
System.out.println("\nSorted by rollno");
for (int i=0; i<ar.size(); i++)
System.out.println(ar.get(i));
}
}
I can sort it if i put the Sortbyroll outside the tools
But i can only submit the student.java file and the tool.java file
so basically i have to do everything inside student class and tool class
and main function cannot be edited...
if i put the sort function static
it said "error: non-static variable this cannot be referenced from a static context"
what should i do ...

you can use compareTo method inside of Student class. change your student model:
class Student implements Comparable<Student>{
int rollno;
String name, address;
// Constructor
public Student(int rollno, String name, String address) {
this.rollno = rollno;
this.name = name;
this.address = address;
}
// Used to print student details in main()
public String toString() {
return this.rollno + " " + this.name +
" " + this.address;
}
public int compareTo(Student model) {
return model.rollno.compareTo(rollno);
}
}
and in main use Collections.sort(response); to sort Array List

Replace your Tools class with the following code.
class tools {
static public ArrayList<Student> sort(ArrayList<Student> arr){
Collections.sort(arr, new Comparator(){
#Override
public int compare(Object s1, Object s2) {
return Integer.compare(((Student)s1).rollno, ((Student)s2).rollno);
}
});
return arr;
}
}

Related

How to print an ArrayList? - java

Question will be below.
public class University {
ArrayList<Student> students;
public University() {
students = new ArrayList<Student>();
}
public void addStudent(Student students) {
this.students.add(students);
}}
public class Student {
String name;
String studentID;
static int studentNumber = 0;
Student(String name, String sID){
this.name = name;
this.studentID = sID;
studentNumber++;
}}
public class TestUniversity {
public static void main(String[] args) {
University universityRegister = new University();
Student studentRegister = new Student("Rachel Green", "a1234");
universityRegister.addStudent(studentRegister);
studentRegister = new Student("Monica Geller", "a12345");
universityRegister.addStudent(studentRegister);
studentRegister = new Student("Ross Geller", "a1111");
universityRegister.addStudent(studentRegister);
System.out.println("Number of student in University: " + Student.studentNumber);
}}
A. I created 3 classes, 1.Student, 2.University, 3.UniversityTester, in 3 different files.
B. I created 3 objects of type Studnet, and stored them in the University class as an ArrayList.
I would like to know how I can print the ArrayList of the students including all information from the UniversityTester class? In the future, I will create another object called Stuff and I will store it in the University class as an ArrayList stuffList. Therefore, I don't want to print the students list from class Student.
Override toString() method in Student class as follows:
import java.util.StringJoiner;
public class Student {
String name;
String studentID;
static int studentNumber = 0;
Student(String name, String sID) {
this.name = name;
this.studentID = sID;
studentNumber++;
}
#Override
public String toString() {
return new StringJoiner(", ", Student.class.getSimpleName() + "[", "]")
.add("name='" + name + "'")
.add("studentID='" + studentID + "'")
.toString();
}
}
Now you can print the array list as follows in TestUniversity:
System.out.println("Student Details: " + universityRegister.students);
Add this to your student class:
#Override
public String toString() {
return String.format("Student: %s , StudentID: %s", name, studentID);
}
And then you can print the entire array like this:
System.out.println("Students: " universityRegister.students);
//Or like this:
for(Student st: universityRegister.students){
System.out.println(st);
}

How to work with array,a value to hold an array of elements

public class Student implements Comparable<Student> {
String fName;
String sName;
String subject[];
int subjectValuation;
public Student(String fName, String sName, String[] subject, int subjectValuation) {
this.fName = fName;
this.sName = sName;
this.subject = subject;
this.subjectValuation = subjectValuation;
}
public String[] getSubject() {
return subject;
}
public String getfName(){
return fName;
}
public String getsName(){
return sName;
}
public void setSubject(String[] subject) {
this.subject = subject;
}
public int getSubjectValuation(){
return subjectValuation;
}
public void setSubjectValuation(int subjectValuation){
this.subjectValuation=subjectValuation;
}
public String toString(){
return " fname "+getfName()+ " sname " +getsName()+ " subjects "+subject+ " valuation "+subjectValuation;
}
public boolean equals(Object o){
if(o!=null && o instanceof Student){
Student s=(Student) o;
if(this.getfName().equalsIgnoreCase(s.fName) && this.getsName().equalsIgnoreCase(s.sName))
return true;
else
return false;
}
return false;
}
public int compareTo(Student o){
return this.subjectValuation-o.subjectValuation;
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class Catalogue {
private ArrayList<Student> s=new ArrayList<>();
//performing 1.
void add(String firstName,String secondName){
s.add(new Student(firstName,secondName,[0],0));
}
//performing 2
void add2(String firstname,String secondName,String subject[],int valuation){
Student accSearch=search(firstname,secondName);
if(accSearch!=null) {
accSearch.setSubject(subject);
accSearch.setSubjectValuation(valuation);
}
else{
System.out.println("couldn't find it");
}
}
//performing 3
void delete(String firstName,String secondName){
Student n=new Student(firstName,secondName,[0],0);
while(s.contains(n)) {
s.remove(n);
}
}
//searching my Student
public Student search(String firstName,String secondName){
for(Student m:s){
if(m.getfName().equalsIgnoreCase(firstName) && m.getsName().equalsIgnoreCase(secondName))
return m;
}
return null;
}
public void listInformation(String firstName,String secondName){
for(Student m:s){
if(m.getfName().equalsIgnoreCase(firstName) &&
m.getsName().equalsIgnoreCase(secondName))
System.out.println(m);
}
}
void printall(){
for(Student m:s){
System.out.println(m);
}
}
//performing 4.
void listValuation(String firstName,String secondName) {
Student searchingFor = search(firstName, secondName);
Iterator<Student> i = s.iterator();
while (i.hasNext()) {
Student s = i.next();
if (s.getfName().equalsIgnoreCase(firstName) && s.getsName().equalsIgnoreCase(secondName))
System.out.println(s.getSubjectValuation());
}
``}
//the average not sure how am i going to do it
void average(String firstName,String secondName){
Student s=search(firstName,secondName);
}
void sort(){
Collections.sort(s);
}
}
public static void main(String[] args) {
Catalogue c=new Catalogue();
c.add("a","b");
c.add("b","c");
c.add("d","f");
c.add("a","b");
// c.listInformation("a","b");
c.delete("a","b");
System.out.println("+");
c.printall();
c.add2("d","f","math",9);
c.printall();
c.add2("f","a","asdsdfd",1);
System.out.println("++");
c.printall();
System.out.println("++++");
c.listValuation("d","f");
}
}
The above class was my Catalogue class.
I have to perform these tasks:
Add a student;
Add for a student subjects and notes;
Delete a student;
Search a student after name and print every grade for every subject;
search a student after name and calculate the average of subject;
I don't know how to assign an array of subjects and grades for student for example I have a student named Jon Jon he can have multiple subjects like Math1,Math2,Math3.... and grades like Math1 grade is 1 Mah2 grade is 2 .....
The 5. is not implemented but I am more interested in how to implement the array of subjects and notes
If I understood your question right you're asking how to combine subjects and grades and put these into an array.
One way you could solve this is implementing a seperate class Subject which also got grades as a attribute.
public class Subject {
private String subject;
private float grade;
//getter and setter methods
}
You can use this class in your class Student:
public class Student implements Comparable<Student> {
String fName;
String sName;
Subject subject[]; //array which can contain multiple subjects. each
//entry got two attributes: the subject itself as String; the grade
//your code
}

Java - How can I create an array of a different class and iterate through it calling its toString method?

I have a Person class with the fields "name" and "phoneNumber" that are set through the constructor. I am trying to create a separate testing class that will create an array of Person and iterate through them by calling to their toString() method.
I am not sure how to do this, any help is appreciated.
Here is my first class which is all I have so far;
public class Person
{
private String name;
private String phoneNumber;
public Person(String name, String phoneNumber)
{
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName()
{
return name;
}
public String getNumber()
{
return phoneNumber;
}
public String getPerson()
{
return name + " " + phoneNumber;
}
#Override
public String toString()
{
return "["+getPerson()+"]";
}
}
Hope this will help,
public class Test {
public static void main(String[] args) {
Person array[] = {new Person("Jason", "123456"), new Person("Karl", "78945"), new Person("Tom", "789456")};
for(int i = 0; i < array.length; i++){
array[i].toString();
//System.out.println(array[i].toString());
}
}
}
class Person
{
private String name;
private String phoneNumber;
public Person(String name, String phoneNumber)
{
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName()
{
return name;
}
public String getNumber()
{
return phoneNumber;
}
public String getPerson()
{
return name + " " + phoneNumber;
}
#Override
public String toString()
{
return "["+getPerson()+"]";
}
}
Save the file as Test.java
Firstly the toString method is for an INDIVIDUAL Person object, and cannot be applied to a whole set, you need to make the method static and have a whole static array defined in the class to be able to go through all instances of the Person class.
private static Person[] pArray = new Person[20];
//I picked 20 randomly, if you want any possible number use an arrayList<Person>
private static int count = 0;
In the constructor
pArray[count] = this;
count++;
Then your toString method:
String list = "[";
for(Person p : this.pArray)
list = list + p.getPerson() + " ,"
list = list + "]";
return list;

Null values when printing out arrayList?

Hi I have created a toStringmethod in one of my classes which can be seen below.
Student Class:
package Practical5;
public class Student extends Person {
//instance variables
private static int MAX_MODULES = 6;
private StudentMode modeOfStudy;
private boolean studentLoan;
private int numEnrolledModules;
//constructor
public Student(String name, String dob, Address address, StudentMode modeOfStudy, boolean studentLoan) {
super(name, dob, address);
this.modeOfStudy = modeOfStudy;
this.studentLoan = studentLoan;
this.numEnrolledModules = 0;
}
//accessors & mutators
public StudentMode getMode() {
return modeOfStudy;
}
public boolean isStudentLoan() {
return studentLoan;
}
public int getNumEnrolledModules() {
return numEnrolledModules;
}
public void setMode(StudentMode modeOfStudy) {
this.modeOfStudy = modeOfStudy;
}
public void setStudentLoan(boolean studentLoan) {
this.studentLoan = studentLoan;
}
public void setNumEnrolledModules(int numEnrolledModules) {
this.numEnrolledModules = numEnrolledModules;
}
#Override
public void purchaseParkingPass() {
System.out.println(getName() + " just purchased a parking pass with student discount.");
}
#Override
public void addModule(String moduleCode) {
if (getNumEnrolledModules() < MAX_MODULES) {
System.out.println(getName() + " successfully registered for the module: " + moduleCode);
}
else {
System.out.println("You are unable to register for " + moduleCode + " as the maximum number of permitted module enrolments has been reached.");
}
}
public String toString() {
return "Student [ ID: " + getId() + "; Name: " + getName() +
"; DOB: " + getDob() + "; Study Mode: " + getMode() +
"; Number of Enrolled Modules: " + getNumEnrolledModules();
}
}
Person Class:
package Practical5;
public abstract class Person {
//instance variables
private static int LAST_ID = 1000 + 1;
private int id;
private String name;
private String dob;
private Address address;
//constructor
public Person(String name, String dob, Address address) {
super();
LAST_ID ++;
this.id = LAST_ID;
}
//accessors & mutators
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getDob() {
return dob;
}
public Address getAddress() {
return address;
}
public void setName(String name) {
this.name = name;
}
public void setDob(String dob) {
this.dob = dob;
}
public void setAddress(Address address) {
this.address = address;
}
//methods
public abstract void purchaseParkingPass();
public abstract void addModule(String moduleCode);
}
I then created a tester class and created a new ArrayList and added these elements to it.
I then created a for loop in order to loop through each element and call the toString method to print out the details of each element but it is returning null values.
Tester Class:
package Practical5;
import java.util.ArrayList;
import java.util.Scanner;
public class UIS_Tester {
public static void main(String[] args) {
Student student1 = new Student("James Black", "07/09/1995" , new Address("Wheeler's Road",10,"Belfast", "BT12 5EG", "Co.Antrim"),StudentMode.Fulltime, false);
Student student2 = new Student("Adam Smith", "12/11/1979" , new Address("Ivy Hill",67,"Belfast", "BT17 7BN", "Co.Antrim"),StudentMode.Parttime, true);
ArrayList<Person> uniPeople = new ArrayList<Person>();
uniPeople.add(student1);
uniPeople.add(student2);
printMenu(uniPeople);
}
public static void printAllDetails(ArrayList<Person> uniPeople) {
for (int i = 0; i < uniPeople.size(); i++) {
System.out.println(uniPeople.get(i).toString());
}
}
}
Output:
Student [ ID: 1002; Name: null; DOB: null; Study Mode: Fulltime; Number of Enrolled Modules: 0
Student [ ID: 1003; Name: null; DOB: null; Study Mode: Parttime; Number of Enrolled Modules: 0
Can anyone help me with this problem? Thanks
public Person(String name, String dob, Address address) {
super();
LAST_ID ++;
this.id = LAST_ID;
}
The constructor completely ignores its three arguments. It doesn't assign them to the corresponding fields, so these fields keep their default value: null.
You have to store the name value in the constructor. Your version did not use the name value.
public Person(String name, String dob, Address address) {
super();
this.name = name; // <== important line
this.dob = dob; // <== important line
this.address = address; // <== important line
LAST_ID ++;
this.id = LAST_ID;
}
Look at the constructor in person and in student, Should use the parameters in the method header.
super(name,dob,address)

Java: how to return an Array?

this is the code, from what I understand, it is suppose to work.
Also when I debug my program, it seems that the array is being filled with the objects that the same method is creating.
But still, when I try to print it, it shows me "null" back agian, like the "return" does not work.
Why is it happening?
public class Course {
String courseName;
String teacherName;
int gradeAv;
static int counter;
static int maxNumOfStudents;
Student studentsArray[] = new Student[5];
int numOfStudents = studentsArray.length;
public Course() {
}
public Course(String courseName) {
this();
this.courseName = courseName;
}
public Course(String courseName, String teacherName) {
this(courseName);
this.courseName = courseName;
this.teacherName = teacherName;
}
public Student[] addStudent(String name, int age, int grade) {
for (int i = 0; i < 5; i++) {
studentsArray[i] = new Student(name, age, grade);
age += 10;
grade += 10;
}
return studentsArray;
}
public void printStudentArray(Student studentArray[]) {
studentArray = this.studentsArray;
for (int i = 0; i < studentsArray.length; i++) {
System.out.println(studentsArray[i]);
}
}
public int gradeAv() {
for (int i = 0; i < studentsArray.length; i++) {
int temp = 0;
if (studentsArray[i].grade > temp) {
gradeAv = temp;
System.out.println(gradeAv);
}
}
return gradeAv;
}
public void printCourse() {
System.out.println("Course: ");
System.out.println("Course Name: " + courseName + ". "
+ "Teacher's Name: " + teacherName + ". "
+ "Number Of Students: " + numOfStudents + ". ");
}
}
This is my main class:
public class MainClass {
public static void main(String[] args) {
Student stud = new Student();
Course cour = new Course("Java", "Ronni");
stud.addStudent("Joe", 23, 100);
stud.printStudent();
System.out.println();
stud.printCourse();
System.out.println();
cour.printStudentArray(cour.studentsArray);
System.out.println();
// cour.gradeAv();
}
}
in
Student stud = new Student();
Course cour = new Course("Java", "Ronni");
stud.addStudent("Joe", 23, 100);
stud.addStudent("Joe", 23, 100); will not add any students to your course. stud is an instance of a completely different class, Student, and the implementation of Student is not in the code you've posted.
call the addStudent method of cour instead of the one for stud
cour.addStudent("Joe", 23, 100);
instead
I would also like to add that there are a lot of curious elements to your code, some of which people have brought up in the comments. It would be tedious to list them all. I'd take a look-through, just to make sure you're not doing redundant things.
Try this for example:
Course class:
import java.util.ArrayList;
import java.util.List;
public class Course {
private List<Student> students = new ArrayList<Student>();
private String teacherName;
private String subjectName;
public Course(String subjectName, String teacherName) {
this.subjectName = subjectName;
this.teacherName = teacherName;
}
public void addStudent(Student student) {
students.add(student);
}
public float getAverageGrade() {
float grade = 0;
for (Student student : students) {
grade += student.getGrade();
}
return grade / students.size();
}
public void printCourse() {
System.out.println("Course "+subjectName+" taught by "+teacherName);
System.out.println("Students:");
printStudents();
System.out.println("Aberage grade: "+getAverageGrade());
}
public void printStudents() {
for (Student student : students) {
System.out.println(student.getName()+"\t age "+student.getAge()+" \t grade "+student.getGrade());
}
}
}
Student class:
public class Student {
private String name;
private int age;
private int grade;
public Student(String name, int age, int grade) {
this.grade = grade;
this.age = age;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}

Categories

Resources