Concept explainers
Is there a way to simataniously get both student names' and roll numbers' to be in ascending order at the same time in one block display? What would that look like? Right now I have to call both methods seperatly in order to see both ascending methods in action and it doesn't look good...Also is it possible to separate the sorting logic from the main method and encapsulate it within a separate class or method that takes the ArrayList of students and the two comparators as arguments?... allowing the program to sort students by different criteria without duplicating the sorting logic?
The attached image is what my program is displaying right now and I want it to display like:
Student [roll number =1, name =Allan, address =620 pioneer st]
Student [roll number =2, name =Billy, address =700 ash st]
Student [roll number =3, name =Chris, address =801 cheney dr]
Student [roll number =4, name =Diana, address =830 washington st]
Student [roll number =5, name =Eliza, address =200 main st]
Student [roll number =6, name =Fedrick, address =504 plymouth ave]
Student [roll number =7, name =George, address =910 oak st]
Student [roll number =8, name =Hannah, address =300 maple ave]
Student [roll number =9, name =Julia, address =100 pine st]
Student [roll number =10, name =Kevin, address =500 elm st]
Source Code:
package application;
public class Student {
introllNum;
String name;
String address;
public Student(introllNum, String name, String address) {
this.rollNum = rollNum;
this.name = name;
this.address = address;
}
//getters and setters
public String getName() {
returnname;
}
publicvoid setName(String name) {
this.name = name;
}
publicint getRollNum() {
returnrollNum;
}
publicvoid setRollNum(introllNum) {
this.rollNum = rollNum;
}
public String getAddress() {
returnaddress;
}
publicvoid setAddress(String address) {
this.address = address;
}
@Override
public String toString()
{
return"Student [roll number =" + rollNum + ", name =" + name + ", address =" + address + "]";
}
}
package application;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Main {
publicstaticvoid main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
int[] rolls = {2,4,1,5,6,7,3,9,8,10};
String[] names = {"Allan", "Chris", "Fedrick", "Diana", "Eliza", "George", "Hannah", "Billy", "Julia", "Kevin"};
String[] addresses = {"620 pioneer st", "801 cheney dr", "504 plymouth ave", "830 washington st", "200 main st", "910 oak st", "300 maple ave", "700 ash st", "100 pine st", "500 elm st"};
for (inti = 0; i < 10; i++) {
introllNum = rolls[i];
String name = names[i];
String address = addresses[i];
students.add(new Student(rollNum, name, address));
}
// Create the GUI
JFrame frame = new JFrame("Sorted Students");
JPanel panel = new JPanel();
JTextArea textArea = new JTextArea(15, 30); // 15 rows, 30 columns
// Append the sorted student information to the text area
StringBuilder string = new StringBuilder();
selectionSortByName(students);
for (Student s : students) {
string.append(s).append("\n");
}
selectionSortByRollNum(students);
for (Student s : students) {
string.append(s).append("\n");
}
textArea.setText(string.toString());
// Add the text area to the panel and the panel to the frame
panel.add(textArea);
frame.add(panel);
// Set frame properties and display it
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
publicstaticvoid selectionSortByName(ArrayList<Student> students) {
StudentComparatorName name = new StudentComparatorName();
for (inti = 0; i < students.size(); i++) {
intminIndex = i;
for (intj = i; j < students.size(); j++) {
//if the element at j is less than element at minIndex then update the minIndex
if(name.compare(students.get(j), students.get(minIndex)) < 0){
minIndex = j;
}
}
Student temp = students.get(i);
//setting the element at minIndex to index i
students.set(i,students.get(minIndex));
students.set(minIndex,temp);
}
}
publicstaticvoid selectionSortByRollNum(ArrayList<Student> students) {
StudentComparatorRollNum sortByRollNo = new StudentComparatorRollNum();
for (inti = 0; i < students.size(); i++) {
intminIndex = i;
for (intj = i; j < students.size(); j++) {
if(sortByRollNo.compare(students.get(j), students.get(minIndex)) < 0){
minIndex = j;
}
}
Student temp = students.get(i);
students.set(i,students.get(minIndex));
students.set(minIndex,temp);
}
}
}
package application;
import java.util.Comparator;
public class StudentComparatorName implements Comparator<Student> {
@Override
publicint compare(Student student1, Student student2) {
//using the string compareTo method to sort the students according to their name
returnstudent1.getName().compareTo(student2.getName());
}
}
package application;
import java.util.Comparator;
public class StudentComparatorRollNum implements Comparator<Student> {
@Override
publicint compare(Student student1, Student student2) {
if(student1.getRollNum() < student2.getRollNum())
return -1;
elseif(student1.getRollNum() > student2.getRollNum())
return 1;
else
return 0;
}
}
Trending nowThis is a popular solution!
Step by stepSolved in 7 steps with 1 images
- Sorting objects in the real world https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html There are 5000 people living in the town. Every day they have new COVID-19 cases. When people show symptom, they go to the hospital and put themselves in the waiting list for testing. A new person is added at the end of the list. Due to the lack of testing kit, all in the list cannot be tested. Hospital has to sort them and select a few. Since the elderly is very weak to the COVID-19, every midnight the doctors sort the people in the list by their age to decide who is taking the test for the next day depending on the availability of testing kit. Input to the program has the form where the first line indicates how many days they will do the operation. For each day, the input starts with the day number, along with the following patient list where each element represents the name of patients and the age. The input ends with the number of available testing kits. The output display, at…arrow_forwardhow would you do this in a simple way? this is for a non graded practice labarrow_forwardUpdate Bresenham’s line (JAVA) method such that you can scale the line before drawing it. Normally, you pass two points and a Graphics’ object to draw line using Bresenham’s algorithm. Now you’ll add scaling factors in arguments for scaling as shown below. public void drawBresenhamLine(Point p1, Point p2, double Sx, double Sy, Graphics g) { //Write your code here } Note: If you use scaling method, then also write Scale method in solution. Answer:arrow_forward
- Create the compareTo method for a class that represents an individual whose first and last names are stored as two Strings. In an alphabetical list of people with last names first and then first names, one individual is "less than" another if they come before the other.(as is typical).arrow_forwardUpdate Bresenham's line (JAVA) method such that you can scale the line before drawing it. Normally, you pass two points and a Graphics' object to draw line using Bresenham's algorithm. Now you'll add scaling factors in arguments for scaling as shown below. public void drawBresenhamline(Point p1, Point p2, double Sx, double Sy, Graphics g) { I/write your code here } Note:If you use scaling method, then also write Scale method in solution.arrow_forwardI need help with this Java program. I got some minor error that I couldn't fix. Checker Classes You will have to implement specific checks to highlight errors found in the source files. We provided an interface Check.java that defines a single method public Optional<Error> lint(String line, int lineNumber) . All the checkers you write should implement this interface and hence, you need to implement the lint method. All of these should return an an Error when one is present with a custom message of your choosing to describe what the error means to the user. If the condition a Check is looking for is not present for a line, should return Optional.empty(). Other class Error.java public Error(int code, int lineNumber, String message) Constructs an Error given the error code, line number and a message. public String toString() Returns a String representation of the error with the line number, error code and message. The representation should be formatted as (replace curly braces with…arrow_forward
- What is the difference in the result of returning the words in a HashSet compared with returning them in an ArrayList?arrow_forwardI need help with this Java program. I got some minor error that I couldn't fix. Checker Classes You will have to implement specific checks to highlight errors found in the source files. We provided an interface Check.java that defines a single method public Optional<Error> lint(String line, int lineNumber) . All the checkers you write should implement this interface and hence, you need to implement the lint method. All of these should return an an Error when one is present with a custom message of your choosing to describe what the error means to the user. If the condition a Check is looking for is not present for a line, should return Optional.empty(). Other class Error.java public Error(int code, int lineNumber, String message) Constructs an Error given the error code, line number and a message. public String toString() Returns a String representation of the error with the line number, error code and message. The representation should be formatted as (replace curly braces with…arrow_forwardImplement the Solver class. In doing so, you are allowed to define other classes to help you (as well as use “built-in” Java classes or the book’s classes). The point of the solver class is the solve method which takes a board/puzzle configuration represented as a 2D array of booleans and returns a char array containing a minimal sequence of moves that will lead to the solved board (all the cells around the edges being filled). The board configuration is passed in as a 5-by-5 boolean array of Booleans with exactly 16 true cells (filled) and 9 false cells (empty). The solve method then returns an array of characters representing a minimal sequence of moves that solves the puzzle. In other words, if the characters from the returned array are used in order as input to the move method on the Board object representing the initial configuration, the resulting board configuration represents the solved board. Furthermore, the solution must be minimal in the sense that there are no solutions…arrow_forward
- Compare and contrast the array and arrayList. Give at least one example that describe when to use arrayList compared to an array.arrow_forwardImplement the Solver class. In doing so, you are allowed to define other classes to help you (as well as use “built-in” Java classes or the book’s classes). The point of the solver class is the solve method which takes a board/puzzle configuration represented as a 2D array of booleans and returns a char array containing a minimal sequence of moves that will lead to the solved board (all the cells around the edges being filled). The board configuration is passed in as a 5-by-5 boolean array of Booleans with exactly 16 true cells (filled) and 9 false cells (empty). The solve method then returns an array of characters representing a minimal sequence of moves that solves the puzzle. In other words, if the characters from the returned array are used in order as input to the move method on the Board object representing the initial configuration, the resulting board configuration represents the solved board. Furthermore, the solution must be minimal in the sense that there are no solutions…arrow_forwardWrite tests and implementarrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education