SlideShare a Scribd company logo
Java question
I am having issues returning the score sort in numerical order for more than 2 entries. I had to
develop an enhancement which allowed the application to sort the list by score. The easiest
solution is probably to create a second student class (perhaps called StudentScore) that
implements the IComparable interface to sort by score rather than by name
StudentSortApp
import java.util.*;
public class StudentSortApp
{
public static void main(String[] args)
{
System.out.println("Welcome to the Student Scores Application."+" ");
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students to enter: ");
int numberofStudents = sc.nextInt();
//arrays storing student name and score
Student[] students = new Student[numberofStudents];
StudentScore [] studentScores = new StudentScore [numberofStudents];
int t = 0;
for (int i = 0; i < numberofStudents; i++)
{
System.out.println("");
String studentLastName = Validator.lastName(sc, "Student " + (i+1) + " Last name: ");
String studentFirstName = Validator.lastName(sc, "Student " + (i+1) + " First name: ");
int studentScore = Validator.validScore(sc, "Student " + (i+1) + " score : ");
students [t] = new Student(studentFirstName, studentLastName , studentScore);
studentScores [t] = new StudentScore(studentFirstName, studentLastName , studentScore);
t = t + 1;
}
//output
System.out.println("");
System.out.println("Last Name Sort");
Arrays.sort(students, 0, numberofStudents);
for(Student i: students)
System.out.println(i.getlastName()+", "+i.getfirstName()+": "+i.getScore());
System.out.println();
System.out.println("Score Sort");
Arrays.sort(studentScores, 0, numberofStudents);
for(StudentScore i: studentScores)
System.out.println(i.getlastName()+", "+i.getfirstName()+": "+i.getScore());
}
}
Validator Class
import java.util.Scanner;
public class Validator
{
public static int validScore(Scanner sc, String prompt)
{
int studentScore = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print (prompt);
studentScore = sc.nextInt();
if (studentScore > 100 || studentScore < 0)
{
System.out.println("Error! You have to enter a score between 0 and 100");
}
else
{
isValid = true;
}
}
return studentScore;
}
public static String lastName(Scanner sc, String prompt)
{
Scanner input = new Scanner(System.in);
String StudentName = "";
boolean isvalid = false;
while (isvalid == false)
{
System.out.print (prompt);
StudentName = input.nextLine();
if (StudentName == null || StudentName.equals(""))
{
System.out.println("Error! You have to enter a name.");
}
else
{
isvalid = true;
}
}
return StudentName;
}
}
Student Class
public class Student implements Comparable
{
private String firstName = "";
private String lastName = "";
private int score = 0;
// Student Class constructor
public Student(String firstName, String lastName, int score)
{
this.firstName = firstName;
this.lastName = lastName;
this.score = score;
}
@Override
public int compareTo(Object nextStudent)
{
Student student =(Student) nextStudent;
if(lastName.equals(student.lastName))
{
return firstName.compareToIgnoreCase(student.firstName);
}
return lastName.compareToIgnoreCase(student.lastName);
}
// returns first Name
public String getfirstName()
{
return firstName;
}
// Returns Last Name
public String getlastName()
{
return lastName;
}
// Returns Student Score
public int getScore()
{
return score;
}
}
StudentScore Class
public class StudentScore implements Comparable
{
private String firstName = "";
private String lastName = "";
private int score = 0;
// StudentScore constructor
public StudentScore(String firstName, String lastName, int score)
{
this.firstName = firstName;
this.lastName = lastName;
this.score = score;
}
@Override
public int compareTo (StudentScore nextStudent)
{
StudentScore student = nextStudent;
if (score > student.score)
{
return score;
}
return student.score;
}
// returns first Name
public String getfirstName()
{
return firstName;
}
// Returns Last Name
public String getlastName()
{
return lastName;
}
// Returns Student Score
public int getScore()
{
return score;
}
}
Output
Last Name Sort
adams, jessica: 63
smith, amy: 75
smith, mike: 88
thomas, kirk: 98
Score Sort
smith, mike: 88
smith, amy: 75
adams, jessica: 63
thomas, kirk: 98
Solution
import java.util.*;
public class StudentSortApp {
public static void main(String[] args) {
System.out.println("Welcome to the Student Scores Application." + " ");
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students to enter: ");
int numberofStudents = sc.nextInt();
// arrays storing student name and score
Student[] students = new Student[numberofStudents];
StudentScore[] studentScores = new StudentScore[numberofStudents];
int t = 0;
for (int i = 0; i < numberofStudents; i++) {
System.out.println("");
String studentLastName = Validator.lastName(sc, "Student "
+ (i + 1) + " Last name: ");
String studentFirstName = Validator.lastName(sc, "Student "
+ (i + 1) + " First name: ");
int studentScore = Validator.validScore(sc, "Student " + (i + 1)
+ " score : ");
students[t] = new Student(studentFirstName, studentLastName,
studentScore);
studentScores[t] = new StudentScore(studentFirstName,
studentLastName, studentScore);
t = t + 1;
}
// output
System.out.println("");
System.out.println("Last Name Sort");
Arrays.sort(students, 0, numberofStudents);
for (Student i : students)
System.out.println(i.getlastName() + ", " + i.getfirstName() + ": "
+ i.getScore());
System.out.println();
System.out.println("Score Sort");
Arrays.sort(studentScores);
for (StudentScore i : studentScores)
System.out.println(i.getlastName() + ", " + i.getfirstName() + ": "
+ i.getScore());
}
}
import java.util.Scanner;
public class Validator {
public static int validScore(Scanner sc, String prompt) {
int studentScore = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
studentScore = sc.nextInt();
if (studentScore > 100 || studentScore < 0) {
System.out
.println("Error! You have to enter a score between 0 and 100");
} else {
isValid = true;
}
}
return studentScore;
}
public static String lastName(Scanner sc, String prompt) {
Scanner input = new Scanner(System.in);
String StudentName = "";
boolean isvalid = false;
while (isvalid == false) {
System.out.print(prompt);
StudentName = input.nextLine();
if (StudentName == null || StudentName.equals("")) {
System.out.println("Error! You have to enter a name.");
}
else
{
isvalid = true;
}
}
return StudentName;
}
}
public class Student implements Comparable {
private String firstName = "";
private String lastName = "";
private int score = 0;
// Student Class constructor
public Student(String firstName, String lastName, int score)
{
this.firstName = firstName;
this.lastName = lastName;
this.score = score;
}
public int compareTo(Object nextStudent) {
Student student = (Student) nextStudent;
if (lastName.equals(student.lastName)) {
return firstName.compareToIgnoreCase(student.firstName);
}
return lastName.compareToIgnoreCase(student.lastName);
}
// returns first Name
public String getfirstName() {
return firstName;
}
// Returns Last Name
public String getlastName() {
return lastName;
}
// Returns Student Score
public int getScore() {
return score;
}
}
public class StudentScore implements Comparable {
private String firstName = "";
private String lastName = "";
private int score = 0;
// StudentScore constructor
public StudentScore(String firstName, String lastName, int score) {
this.firstName = firstName;
this.lastName = lastName;
this.score = score;
}
public int compareTo(StudentScore nextStudent)
{
return Integer.compare(this.score, nextStudent.score);
}
// returns first Name
public String getfirstName() {
return firstName;
}
// Returns Last Name
public String getlastName() {
return lastName;
}
// Returns Student Score
public int getScore() {
return score;
}
}
output
Welcome to the Student Scores Application.
Enter number of students to enter: 4
Student 1 Last name: mark
Student 1 First name: smith
Student 1 score : 98
Student 2 Last name: koti
Student 2 First name: b
Student 2 score : 10
Student 3 Last name: john
Student 3 First name: abraham
Student 3 score : 65
Student 4 Last name: ramu
Student 4 First name: rma
Student 4 score : 25
Last Name Sort
john, abraham: 65
koti, b: 10
mark, smith: 98
ramu, rma: 25
Score Sort
koti, b: 10
ramu, rma: 25
john, abraham: 65
mark, smith: 98

More Related Content

Similar to Java questionI am having issues returning the score sort in numeri.pdf

In your Person classAdd a constant field to store the current yea.pdf
In your Person classAdd a constant field to store the current yea.pdfIn your Person classAdd a constant field to store the current yea.pdf
In your Person classAdd a constant field to store the current yea.pdfarihanthtextiles
 
Assignment 7
Assignment 7Assignment 7
Assignment 7IIUM
 
please help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdfplease help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdfarishmarketing21
 
Im getting List Full when I try to add 2nd student.Driver..pdf
Im getting List Full when I try to add 2nd student.Driver..pdfIm getting List Full when I try to add 2nd student.Driver..pdf
Im getting List Full when I try to add 2nd student.Driver..pdfforwardcom41
 
HELP IN JAVACreate a main method and use these input files to tes.pdf
HELP IN JAVACreate a main method and use these input files to tes.pdfHELP IN JAVACreate a main method and use these input files to tes.pdf
HELP IN JAVACreate a main method and use these input files to tes.pdffatoryoutlets
 
Define a class named Doctor whose objects are records for clinic’s d.pdf
Define a class named Doctor whose objects are records for clinic’s d.pdfDefine a class named Doctor whose objects are records for clinic’s d.pdf
Define a class named Doctor whose objects are records for clinic’s d.pdfMALASADHNANI
 
Hi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdfHi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdffashioncollection2
 
So Far I have these two classes but I need help with my persontest c.pdf
So Far I have these two classes but I need help with my persontest c.pdfSo Far I have these two classes but I need help with my persontest c.pdf
So Far I have these two classes but I need help with my persontest c.pdfarihantgiftgallery
 
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdfJAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdfcalderoncasto9163
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywordsmanish kumar
 
JAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfJAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfRohitkumarYadav80
 

Similar to Java questionI am having issues returning the score sort in numeri.pdf (14)

In your Person classAdd a constant field to store the current yea.pdf
In your Person classAdd a constant field to store the current yea.pdfIn your Person classAdd a constant field to store the current yea.pdf
In your Person classAdd a constant field to store the current yea.pdf
 
Assignment 7
Assignment 7Assignment 7
Assignment 7
 
please help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdfplease help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdf
 
OOP Lab Report.docx
OOP Lab Report.docxOOP Lab Report.docx
OOP Lab Report.docx
 
Im getting List Full when I try to add 2nd student.Driver..pdf
Im getting List Full when I try to add 2nd student.Driver..pdfIm getting List Full when I try to add 2nd student.Driver..pdf
Im getting List Full when I try to add 2nd student.Driver..pdf
 
HELP IN JAVACreate a main method and use these input files to tes.pdf
HELP IN JAVACreate a main method and use these input files to tes.pdfHELP IN JAVACreate a main method and use these input files to tes.pdf
HELP IN JAVACreate a main method and use these input files to tes.pdf
 
Define a class named Doctor whose objects are records for clinic’s d.pdf
Define a class named Doctor whose objects are records for clinic’s d.pdfDefine a class named Doctor whose objects are records for clinic’s d.pdf
Define a class named Doctor whose objects are records for clinic’s d.pdf
 
Hi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdfHi, I need help with a java programming project. specifically practi.pdf
Hi, I need help with a java programming project. specifically practi.pdf
 
So Far I have these two classes but I need help with my persontest c.pdf
So Far I have these two classes but I need help with my persontest c.pdfSo Far I have these two classes but I need help with my persontest c.pdf
So Far I have these two classes but I need help with my persontest c.pdf
 
Java Methods
Java MethodsJava Methods
Java Methods
 
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdfJAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Unit-3 Practice Programs-5.docx
Unit-3 Practice Programs-5.docxUnit-3 Practice Programs-5.docx
Unit-3 Practice Programs-5.docx
 
JAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfJAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdf
 

More from forwardcom41

Hello!Can someone help me to answer Task4 and Task7Complete T.pdf
Hello!Can someone help me to answer Task4 and Task7Complete T.pdfHello!Can someone help me to answer Task4 and Task7Complete T.pdf
Hello!Can someone help me to answer Task4 and Task7Complete T.pdfforwardcom41
 
Hey I need help creating this code using Visual Studio (Basic) 2015.pdf
Hey I need help creating this code using Visual Studio (Basic) 2015.pdfHey I need help creating this code using Visual Studio (Basic) 2015.pdf
Hey I need help creating this code using Visual Studio (Basic) 2015.pdfforwardcom41
 
Given technology today, would it be more feasible than in the pa.pdf
Given technology today, would it be more feasible than in the pa.pdfGiven technology today, would it be more feasible than in the pa.pdf
Given technology today, would it be more feasible than in the pa.pdfforwardcom41
 
Explain the difference between a contaminated culture and a mix c.pdf
Explain the difference between a contaminated culture and a mix c.pdfExplain the difference between a contaminated culture and a mix c.pdf
Explain the difference between a contaminated culture and a mix c.pdfforwardcom41
 
Explain in detail how OFDM helps mitigates multipath fading effects..pdf
Explain in detail how OFDM helps mitigates multipath fading effects..pdfExplain in detail how OFDM helps mitigates multipath fading effects..pdf
Explain in detail how OFDM helps mitigates multipath fading effects..pdfforwardcom41
 
Complete a scientific inquiry research using three credible sources..pdf
Complete a scientific inquiry research using three credible sources..pdfComplete a scientific inquiry research using three credible sources..pdf
Complete a scientific inquiry research using three credible sources..pdfforwardcom41
 
Combine the keypad and LCD codes in compliance to the following requ.pdf
Combine the keypad and LCD codes in compliance to the following requ.pdfCombine the keypad and LCD codes in compliance to the following requ.pdf
Combine the keypad and LCD codes in compliance to the following requ.pdfforwardcom41
 
Describe and illustrate the use of a bank reconciliation in controll.pdf
Describe and illustrate the use of a bank reconciliation in controll.pdfDescribe and illustrate the use of a bank reconciliation in controll.pdf
Describe and illustrate the use of a bank reconciliation in controll.pdfforwardcom41
 
Why is it important for a trainer (trainers) to understand the commu.pdf
Why is it important for a trainer (trainers) to understand the commu.pdfWhy is it important for a trainer (trainers) to understand the commu.pdf
Why is it important for a trainer (trainers) to understand the commu.pdfforwardcom41
 
What are the various portals an enterprise can use What is the func.pdf
What are the various portals an enterprise can use What is the func.pdfWhat are the various portals an enterprise can use What is the func.pdf
What are the various portals an enterprise can use What is the func.pdfforwardcom41
 
What is the nature of thermal energy What is heat at the atomic lev.pdf
What is the nature of thermal energy What is heat at the atomic lev.pdfWhat is the nature of thermal energy What is heat at the atomic lev.pdf
What is the nature of thermal energy What is heat at the atomic lev.pdfforwardcom41
 
w Hstory Bookmarks Window Help Apple Bing Google Taho0 NewaDetals MIN.pdf
w Hstory Bookmarks Window Help Apple Bing Google Taho0 NewaDetals MIN.pdfw Hstory Bookmarks Window Help Apple Bing Google Taho0 NewaDetals MIN.pdf
w Hstory Bookmarks Window Help Apple Bing Google Taho0 NewaDetals MIN.pdfforwardcom41
 
Which of the following is not one of the ethical standards included .pdf
Which of the following is not one of the ethical standards included .pdfWhich of the following is not one of the ethical standards included .pdf
Which of the following is not one of the ethical standards included .pdfforwardcom41
 
Using the guidance from ASC 855-10-55-1 and 855-10-55-2 Answer the f.pdf
Using the guidance from ASC 855-10-55-1 and 855-10-55-2 Answer the f.pdfUsing the guidance from ASC 855-10-55-1 and 855-10-55-2 Answer the f.pdf
Using the guidance from ASC 855-10-55-1 and 855-10-55-2 Answer the f.pdfforwardcom41
 
why we need mixed methodology for researchSolutionMixed metho.pdf
why we need mixed methodology for researchSolutionMixed metho.pdfwhy we need mixed methodology for researchSolutionMixed metho.pdf
why we need mixed methodology for researchSolutionMixed metho.pdfforwardcom41
 
What property doesnt apply to fluids Newtons second, cons of ene.pdf
What property doesnt apply to fluids Newtons second, cons of ene.pdfWhat property doesnt apply to fluids Newtons second, cons of ene.pdf
What property doesnt apply to fluids Newtons second, cons of ene.pdfforwardcom41
 
What is the threat to culture by a read-only world, and how do t.pdf
What is the threat to culture by a read-only world, and how do t.pdfWhat is the threat to culture by a read-only world, and how do t.pdf
What is the threat to culture by a read-only world, and how do t.pdfforwardcom41
 
What is one hypothesis to explain why there are more endemic bird sp.pdf
What is one hypothesis to explain why there are more endemic bird sp.pdfWhat is one hypothesis to explain why there are more endemic bird sp.pdf
What is one hypothesis to explain why there are more endemic bird sp.pdfforwardcom41
 
What are the ethical tensions in advertisingWho are the responsib.pdf
What are the ethical tensions in advertisingWho are the responsib.pdfWhat are the ethical tensions in advertisingWho are the responsib.pdf
What are the ethical tensions in advertisingWho are the responsib.pdfforwardcom41
 
Use the following information to answer the next Question. The graph.pdf
Use the following information to answer the next Question.  The graph.pdfUse the following information to answer the next Question.  The graph.pdf
Use the following information to answer the next Question. The graph.pdfforwardcom41
 

More from forwardcom41 (20)

Hello!Can someone help me to answer Task4 and Task7Complete T.pdf
Hello!Can someone help me to answer Task4 and Task7Complete T.pdfHello!Can someone help me to answer Task4 and Task7Complete T.pdf
Hello!Can someone help me to answer Task4 and Task7Complete T.pdf
 
Hey I need help creating this code using Visual Studio (Basic) 2015.pdf
Hey I need help creating this code using Visual Studio (Basic) 2015.pdfHey I need help creating this code using Visual Studio (Basic) 2015.pdf
Hey I need help creating this code using Visual Studio (Basic) 2015.pdf
 
Given technology today, would it be more feasible than in the pa.pdf
Given technology today, would it be more feasible than in the pa.pdfGiven technology today, would it be more feasible than in the pa.pdf
Given technology today, would it be more feasible than in the pa.pdf
 
Explain the difference between a contaminated culture and a mix c.pdf
Explain the difference between a contaminated culture and a mix c.pdfExplain the difference between a contaminated culture and a mix c.pdf
Explain the difference between a contaminated culture and a mix c.pdf
 
Explain in detail how OFDM helps mitigates multipath fading effects..pdf
Explain in detail how OFDM helps mitigates multipath fading effects..pdfExplain in detail how OFDM helps mitigates multipath fading effects..pdf
Explain in detail how OFDM helps mitigates multipath fading effects..pdf
 
Complete a scientific inquiry research using three credible sources..pdf
Complete a scientific inquiry research using three credible sources..pdfComplete a scientific inquiry research using three credible sources..pdf
Complete a scientific inquiry research using three credible sources..pdf
 
Combine the keypad and LCD codes in compliance to the following requ.pdf
Combine the keypad and LCD codes in compliance to the following requ.pdfCombine the keypad and LCD codes in compliance to the following requ.pdf
Combine the keypad and LCD codes in compliance to the following requ.pdf
 
Describe and illustrate the use of a bank reconciliation in controll.pdf
Describe and illustrate the use of a bank reconciliation in controll.pdfDescribe and illustrate the use of a bank reconciliation in controll.pdf
Describe and illustrate the use of a bank reconciliation in controll.pdf
 
Why is it important for a trainer (trainers) to understand the commu.pdf
Why is it important for a trainer (trainers) to understand the commu.pdfWhy is it important for a trainer (trainers) to understand the commu.pdf
Why is it important for a trainer (trainers) to understand the commu.pdf
 
What are the various portals an enterprise can use What is the func.pdf
What are the various portals an enterprise can use What is the func.pdfWhat are the various portals an enterprise can use What is the func.pdf
What are the various portals an enterprise can use What is the func.pdf
 
What is the nature of thermal energy What is heat at the atomic lev.pdf
What is the nature of thermal energy What is heat at the atomic lev.pdfWhat is the nature of thermal energy What is heat at the atomic lev.pdf
What is the nature of thermal energy What is heat at the atomic lev.pdf
 
w Hstory Bookmarks Window Help Apple Bing Google Taho0 NewaDetals MIN.pdf
w Hstory Bookmarks Window Help Apple Bing Google Taho0 NewaDetals MIN.pdfw Hstory Bookmarks Window Help Apple Bing Google Taho0 NewaDetals MIN.pdf
w Hstory Bookmarks Window Help Apple Bing Google Taho0 NewaDetals MIN.pdf
 
Which of the following is not one of the ethical standards included .pdf
Which of the following is not one of the ethical standards included .pdfWhich of the following is not one of the ethical standards included .pdf
Which of the following is not one of the ethical standards included .pdf
 
Using the guidance from ASC 855-10-55-1 and 855-10-55-2 Answer the f.pdf
Using the guidance from ASC 855-10-55-1 and 855-10-55-2 Answer the f.pdfUsing the guidance from ASC 855-10-55-1 and 855-10-55-2 Answer the f.pdf
Using the guidance from ASC 855-10-55-1 and 855-10-55-2 Answer the f.pdf
 
why we need mixed methodology for researchSolutionMixed metho.pdf
why we need mixed methodology for researchSolutionMixed metho.pdfwhy we need mixed methodology for researchSolutionMixed metho.pdf
why we need mixed methodology for researchSolutionMixed metho.pdf
 
What property doesnt apply to fluids Newtons second, cons of ene.pdf
What property doesnt apply to fluids Newtons second, cons of ene.pdfWhat property doesnt apply to fluids Newtons second, cons of ene.pdf
What property doesnt apply to fluids Newtons second, cons of ene.pdf
 
What is the threat to culture by a read-only world, and how do t.pdf
What is the threat to culture by a read-only world, and how do t.pdfWhat is the threat to culture by a read-only world, and how do t.pdf
What is the threat to culture by a read-only world, and how do t.pdf
 
What is one hypothesis to explain why there are more endemic bird sp.pdf
What is one hypothesis to explain why there are more endemic bird sp.pdfWhat is one hypothesis to explain why there are more endemic bird sp.pdf
What is one hypothesis to explain why there are more endemic bird sp.pdf
 
What are the ethical tensions in advertisingWho are the responsib.pdf
What are the ethical tensions in advertisingWho are the responsib.pdfWhat are the ethical tensions in advertisingWho are the responsib.pdf
What are the ethical tensions in advertisingWho are the responsib.pdf
 
Use the following information to answer the next Question. The graph.pdf
Use the following information to answer the next Question.  The graph.pdfUse the following information to answer the next Question.  The graph.pdf
Use the following information to answer the next Question. The graph.pdf
 

Recently uploaded

The Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. HenryThe Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. HenryEugene Lysak
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxricssacare
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleCeline George
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfVivekanand Anglo Vedic Academy
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXMIRIAMSALINAS13
 
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...Denish Jangid
 
Gyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptxGyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptxShibin Azad
 
The impact of social media on mental health and well-being has been a topic o...
The impact of social media on mental health and well-being has been a topic o...The impact of social media on mental health and well-being has been a topic o...
The impact of social media on mental health and well-being has been a topic o...sanghavirahi2
 
[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online PresentationGDSCYCCE
 
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdf
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdfTelling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdf
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdfTechSoup
 
Salient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxSalient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxakshayaramakrishnan21
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345beazzy04
 
size separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticssize separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticspragatimahajan3
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptSourabh Kumar
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePedroFerreira53928
 
Keeping Your Information Safe with Centralized Security Services
Keeping Your Information Safe with Centralized Security ServicesKeeping Your Information Safe with Centralized Security Services
Keeping Your Information Safe with Centralized Security ServicesTechSoup
 
Application of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesApplication of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesRased Khan
 

Recently uploaded (20)

The Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. HenryThe Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. Henry
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
Operations Management - Book1.p  - Dr. Abdulfatah A. SalemOperations Management - Book1.p  - Dr. Abdulfatah A. Salem
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...Basic Civil Engineering Notes of Chapter-6,  Topic- Ecosystem, Biodiversity G...
Basic Civil Engineering Notes of Chapter-6, Topic- Ecosystem, Biodiversity G...
 
Gyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptxGyanartha SciBizTech Quiz slideshare.pptx
Gyanartha SciBizTech Quiz slideshare.pptx
 
The impact of social media on mental health and well-being has been a topic o...
The impact of social media on mental health and well-being has been a topic o...The impact of social media on mental health and well-being has been a topic o...
The impact of social media on mental health and well-being has been a topic o...
 
[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation[GDSC YCCE] Build with AI Online Presentation
[GDSC YCCE] Build with AI Online Presentation
 
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdf
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdfTelling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdf
Telling Your Story_ Simple Steps to Build Your Nonprofit's Brand Webinar.pdf
 
Salient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxSalient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
size separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticssize separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceutics
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
NCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdfNCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdf
 
Keeping Your Information Safe with Centralized Security Services
Keeping Your Information Safe with Centralized Security ServicesKeeping Your Information Safe with Centralized Security Services
Keeping Your Information Safe with Centralized Security Services
 
Application of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesApplication of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matrices
 

Java questionI am having issues returning the score sort in numeri.pdf

  • 1. Java question I am having issues returning the score sort in numerical order for more than 2 entries. I had to develop an enhancement which allowed the application to sort the list by score. The easiest solution is probably to create a second student class (perhaps called StudentScore) that implements the IComparable interface to sort by score rather than by name StudentSortApp import java.util.*; public class StudentSortApp { public static void main(String[] args) { System.out.println("Welcome to the Student Scores Application."+" "); Scanner sc = new Scanner(System.in); System.out.print("Enter number of students to enter: "); int numberofStudents = sc.nextInt(); //arrays storing student name and score Student[] students = new Student[numberofStudents]; StudentScore [] studentScores = new StudentScore [numberofStudents]; int t = 0; for (int i = 0; i < numberofStudents; i++) { System.out.println(""); String studentLastName = Validator.lastName(sc, "Student " + (i+1) + " Last name: "); String studentFirstName = Validator.lastName(sc, "Student " + (i+1) + " First name: "); int studentScore = Validator.validScore(sc, "Student " + (i+1) + " score : "); students [t] = new Student(studentFirstName, studentLastName , studentScore); studentScores [t] = new StudentScore(studentFirstName, studentLastName , studentScore); t = t + 1; } //output System.out.println("");
  • 2. System.out.println("Last Name Sort"); Arrays.sort(students, 0, numberofStudents); for(Student i: students) System.out.println(i.getlastName()+", "+i.getfirstName()+": "+i.getScore()); System.out.println(); System.out.println("Score Sort"); Arrays.sort(studentScores, 0, numberofStudents); for(StudentScore i: studentScores) System.out.println(i.getlastName()+", "+i.getfirstName()+": "+i.getScore()); } } Validator Class import java.util.Scanner; public class Validator { public static int validScore(Scanner sc, String prompt) { int studentScore = 0; boolean isValid = false; while (isValid == false) { System.out.print (prompt); studentScore = sc.nextInt(); if (studentScore > 100 || studentScore < 0) { System.out.println("Error! You have to enter a score between 0 and 100"); } else { isValid = true; } }
  • 3. return studentScore; } public static String lastName(Scanner sc, String prompt) { Scanner input = new Scanner(System.in); String StudentName = ""; boolean isvalid = false; while (isvalid == false) { System.out.print (prompt); StudentName = input.nextLine(); if (StudentName == null || StudentName.equals("")) { System.out.println("Error! You have to enter a name."); } else { isvalid = true; } } return StudentName; } } Student Class public class Student implements Comparable {
  • 4. private String firstName = ""; private String lastName = ""; private int score = 0; // Student Class constructor public Student(String firstName, String lastName, int score) { this.firstName = firstName; this.lastName = lastName; this.score = score; } @Override public int compareTo(Object nextStudent) { Student student =(Student) nextStudent; if(lastName.equals(student.lastName)) { return firstName.compareToIgnoreCase(student.firstName); } return lastName.compareToIgnoreCase(student.lastName); } // returns first Name public String getfirstName() { return firstName; } // Returns Last Name
  • 5. public String getlastName() { return lastName; } // Returns Student Score public int getScore() { return score; } } StudentScore Class public class StudentScore implements Comparable { private String firstName = ""; private String lastName = ""; private int score = 0; // StudentScore constructor public StudentScore(String firstName, String lastName, int score) { this.firstName = firstName; this.lastName = lastName; this.score = score; } @Override public int compareTo (StudentScore nextStudent) { StudentScore student = nextStudent; if (score > student.score) { return score; } return student.score; }
  • 6. // returns first Name public String getfirstName() { return firstName; } // Returns Last Name public String getlastName() { return lastName; } // Returns Student Score public int getScore() { return score; } } Output Last Name Sort adams, jessica: 63 smith, amy: 75 smith, mike: 88 thomas, kirk: 98 Score Sort smith, mike: 88 smith, amy: 75 adams, jessica: 63 thomas, kirk: 98 Solution import java.util.*; public class StudentSortApp { public static void main(String[] args) {
  • 7. System.out.println("Welcome to the Student Scores Application." + " "); Scanner sc = new Scanner(System.in); System.out.print("Enter number of students to enter: "); int numberofStudents = sc.nextInt(); // arrays storing student name and score Student[] students = new Student[numberofStudents]; StudentScore[] studentScores = new StudentScore[numberofStudents]; int t = 0; for (int i = 0; i < numberofStudents; i++) { System.out.println(""); String studentLastName = Validator.lastName(sc, "Student " + (i + 1) + " Last name: "); String studentFirstName = Validator.lastName(sc, "Student " + (i + 1) + " First name: "); int studentScore = Validator.validScore(sc, "Student " + (i + 1) + " score : "); students[t] = new Student(studentFirstName, studentLastName, studentScore); studentScores[t] = new StudentScore(studentFirstName, studentLastName, studentScore); t = t + 1; } // output System.out.println(""); System.out.println("Last Name Sort"); Arrays.sort(students, 0, numberofStudents); for (Student i : students) System.out.println(i.getlastName() + ", " + i.getfirstName() + ": " + i.getScore()); System.out.println(); System.out.println("Score Sort"); Arrays.sort(studentScores); for (StudentScore i : studentScores) System.out.println(i.getlastName() + ", " + i.getfirstName() + ": " + i.getScore()); }
  • 8. } import java.util.Scanner; public class Validator { public static int validScore(Scanner sc, String prompt) { int studentScore = 0; boolean isValid = false; while (isValid == false) { System.out.print(prompt); studentScore = sc.nextInt(); if (studentScore > 100 || studentScore < 0) { System.out .println("Error! You have to enter a score between 0 and 100"); } else { isValid = true; } } return studentScore; } public static String lastName(Scanner sc, String prompt) { Scanner input = new Scanner(System.in); String StudentName = ""; boolean isvalid = false; while (isvalid == false) { System.out.print(prompt); StudentName = input.nextLine(); if (StudentName == null || StudentName.equals("")) { System.out.println("Error! You have to enter a name."); } else { isvalid = true; } } return StudentName; } }
  • 9. public class Student implements Comparable { private String firstName = ""; private String lastName = ""; private int score = 0; // Student Class constructor public Student(String firstName, String lastName, int score) { this.firstName = firstName; this.lastName = lastName; this.score = score; } public int compareTo(Object nextStudent) { Student student = (Student) nextStudent; if (lastName.equals(student.lastName)) { return firstName.compareToIgnoreCase(student.firstName); } return lastName.compareToIgnoreCase(student.lastName); } // returns first Name public String getfirstName() { return firstName; } // Returns Last Name public String getlastName() { return lastName; } // Returns Student Score public int getScore() { return score; } } public class StudentScore implements Comparable { private String firstName = ""; private String lastName = ""; private int score = 0; // StudentScore constructor
  • 10. public StudentScore(String firstName, String lastName, int score) { this.firstName = firstName; this.lastName = lastName; this.score = score; } public int compareTo(StudentScore nextStudent) { return Integer.compare(this.score, nextStudent.score); } // returns first Name public String getfirstName() { return firstName; } // Returns Last Name public String getlastName() { return lastName; } // Returns Student Score public int getScore() { return score; } } output Welcome to the Student Scores Application. Enter number of students to enter: 4 Student 1 Last name: mark Student 1 First name: smith Student 1 score : 98 Student 2 Last name: koti Student 2 First name: b Student 2 score : 10 Student 3 Last name: john Student 3 First name: abraham Student 3 score : 65 Student 4 Last name: ramu Student 4 First name: rma
  • 11. Student 4 score : 25 Last Name Sort john, abraham: 65 koti, b: 10 mark, smith: 98 ramu, rma: 25 Score Sort koti, b: 10 ramu, rma: 25 john, abraham: 65 mark, smith: 98