Trying to get the right value answer for my code - java

Below is the code i have written for a student class and main method. I am having two problems. Firstly, when i try and put main as its own class, if fails to run and compile saying there is an erroneous error with main not being able to reference and create the student classes within main.
Second problem, the last line where it prints out the highest average mark, always prints out 0.0, and i cannot for the life of me work out why.
Can anyone give me the solution to either problems?
I am using NetBeans.
package student;
public class Student {
private String name, id;
private int[] score = new int[3];
public Student()
{
}
public Student(String stName, String stID, int stScore[]) {
this.name = stName;
this.id = stID;
this.score = stScore;
}
public void setName(String nameIn)
{
name = nameIn;
}
public String getName()
{
return name;
}
public double avScore()
{
double total = 0;
int to = 0;
int adder = 0;
for (int i=0; i<score.length; i++)
{
score[i] = adder;
total = total + adder;
}
total = total / score.length;
return total;
}
public void printOut() {
System.out.println("Student Name is: " + name) ;
System.out.println("Student ID is: " + id);
System.out.println("Student scores are: ");
for (int i=0; i<score.length; i++)
{
System.out.println(score[i]);
}
}
public static void main(String args []) {
Student stud1 = new Student("Nico Del Pellegrino", "up660537", new int[] {1, 2, 3});
Student stud2 = new Student("Dylan Scott", "up652312", new int[] {5, 7, 13});
stud1.printOut();
stud2.printOut();
Student stud3 = new Student();
stud3.id = "up645658";
stud3.name = "Alex Barrett";
stud3.score = new int[]{5, 10, 15};
stud3.printOut();
double stud1Score = stud1.avScore();
double stud2Score = stud2.avScore();
double stud3Score = stud3.avScore();
double[] scoreList = {stud1Score, stud2Score, stud3Score};
double highestMark = 0;
for (int i=0; i<scoreList.length;)
{
if(scoreList[i]>highestMark)
{
highestMark = scoreList[i];
i++;
}
else
{
i++;
}
}
System.out.println("The highest average mark is: " + highestMark);
}
}
EDIT:
This is the code in its separate classes, and the error message that occurs when running main.
package student;
public class Student {
private String name, id;
private int[] score = new int[3];
public Student() {
}
public Student(String stName, String stID, int stScore[]) {
this.name = stName;
this.id = stID;
this.score = stScore;
}
public void setName(String nameIn) {
name = nameIn;
}
public String getName() {
return name;
}
public double avScore() {
double total = 0;
int to = 0;
for (int i = 0; i < score.length; i++) {
total = total + score[i];
}
total = total / score.length;
return total;
}
public void printOut() {
System.out.println("Student Name is: " + name);
System.out.println("Student ID is: " + id);
System.out.println("Student scores are: ");
for (int i = 0; i < score.length; i++) {
System.out.println(score[i]);
}
}
}
package Student;
import Student.*;
public class Main {
public static void main(String args []) {
//Create two student objects stud1 and stud2 here
Student stud1 = new Student("Nico Del Pellegrino", "up660537", new int[] {1, 2, 3});
Student stud2 = new Student("Dylan Scott", "up652312", new int[] {5, 7, 13});
//Display information for the two objects
stud1.printOut();
stud2.printOut();
//Create third student object stud3 here
Student stud3 = new Student();
// change object id
stud3.id = "up645658";
// change object name
stud3.name = "Alex Barrett";
// change object exam scores
stud3.score = new int[]{5, 10, 15};
stud3.printOut();
// Find out which student is with the highest average score
int stud1Score = stud1.avScore();
int stud2Score = stud2.avScore();
int stud3Score = stud3.avScore();
//Display his/her details here
}
}
//run:
//Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree //type: Student.Student
// at Student.Main.main(Main.java:9)
//Java Result: 1
//BUILD SUCCESSFUL (total time: 0 seconds)

Your assignment on this line is incorrect:
score[i] = adder;
You initialized adder to 0, so you are effectively placing zeroes throughout your array. No wonder you get 0.0 for the average. Instead of
score[i] = adder;
total = total + adder;
You don't even need adder, just use:
total = total + score[i];

Related

How the Arrays.sort works after the Comparable interface is done in java

The code is to sort the and print students name according to their marks in descending order. In a class there are ‘n’ number of students. They have three different subjects: Data Structures, Algorithm Design & Analysis and Operating Systems. Marks for each subject of all the students are provided to you. You have to tell the position of each student in the class. Print the names of each student according to their position in class. Tie is broken on the basis of their roll numbers. Between two students having same marks, the one with less roll number will have higher rank. The input is provided in order of roll number.
I am able to implement the code in which I made a pair class to sort according to their marks and stored all the object in the array. After that I used Array.sort to sort the array.
So how did the Arrays.sort(pair) sorted the array on what basis.
import java.util.*;
public class Main{
static class pair implements Comparable<pair>{
int marks;
String name;
public pair(int m, String n){
this.marks = m;
this.name = n;
}
#Override
public int compareTo(pair p){
return p.marks - this.marks;
}
}
public static void main(String args[]){
Scanner in = new Scanner(System.in);
// String sn = in.nextLine();
int n = in.nextInt();
pair[] arr= new pair[n];
for(int i =0;i< n;i++){
String name = in.next();
int sum = 0;
for(int j = 0;j<3;j++){
int num = in.nextInt();
sum += num;
}
int marks = sum ;
arr[i]= new pair(marks,name);
}
Arrays.sort(arr);
for(int i = 0;i<arr.length;i++){
System.out.println(i+1 +" "+arr[i].name);
}
}
}
In the below code comparator is doing compare on basis of marks. Array.sort uses a customized comparator.
package stackoverflow;
import java.util.Arrays;
import java.util.Comparator;
class Student {
int rollno, marks;
String name;
public Student(int rollno, int marks, String name) {
this.rollno = rollno;
this.name = name;
this.marks = marks;
}
public String toString() {
return this.rollno + " " + this.name + " " + this.marks;
}
}
class Sortbymarks implements Comparator<Student> {
public int compare(Student a, Student b) {
return b.marks - a.marks;
}
}
public class ArraySort {
public static void main(String[] args) {
Student[] arr = { new Student(111, 150, "abc"), new Student(131, 100, "abcd"), new Student(121, 120, "xyz"),
new Student(191, 150, "txy") };
System.out.println("Unsorted");
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
Arrays.sort(arr, new Sortbymarks());
System.out.println("Sorted by marks");
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
Here is my answer. I want to know how Arrays.sort() sorts the object pair after it has already been sorted according to their marks.
import java.util.*;
public class Main{
static class pair implements Comparable<pair>{
int marks;
String name;
public pair(int m, String n){
this.marks = m;
this.name = n;
}
#Override
public int compareTo(pair p){
return p.marks - this.marks;
}
}
public static void main(String args[]){
Scanner in = new Scanner(System.in);
// String sn = in.nextLine();
int n = in.nextInt();
pair[] arr= new pair[n];
for(int i =0;i< n;i++){
String name = in.next();
int sum = 0;
for(int j = 0;j<3;j++){
int num = in.nextInt();
sum += num;
}
int marks = sum ;
arr[i]= new pair(marks,name);
}
Arrays.sort(arr);
for(int i = 0;i<arr.length;i++){
System.out.println(i+1 +" "+arr[i].name);
}
}
}

Is there another way to get the index without using the index of the array? ex. Not using Array[5]

So, I was wondering if there is any way to get the Highest Name without using Names[5] ?
int[] points = { 68, 87, 91, 30, 56, 99, 91 };
String[] Names = { "Billon", "Bob", "Barbie", "Beny", "Bardon", "Becks", "Benji" };
showHighest(scores, Names);
int a = findThatName(Names, "Benji");
if (a == -1)
System.out.print("\nBenji is not on the list");
else
System.out.printf("\nName: %s had %s points", Names[a], points[a]);
a = findThatName(Names, "Fed");
if (a == -1)
System.out.print("\nFed was not on the list");
else
System.out.printf("\nName: %s had %s points", Names[a], points[a]);
}
public static void showHighest(int[] points, String[] Names) {
int max = points[0];
for (int a = 1; a < points.length; a++) {
if (points[a] > max)
max = points[a];
}
System.out.printf("Highest Name: %s Highest Points: %s", Names[5], max);
}
public static int findThatName(String[] Names, String name) {
int index = -1;
for (int a = 0; a < Names.length; a++) {
if (Names[a].equals(name)) {
index = a;
break;
}
}
return index;
}
}
Specifically, within the showBest method. Instead of using Names[5], am I able to get something like Names[i]? Or maybe how would I use the index of the max score to be the same index of Names?
edit: Sorry I had to change the wording of the code...
You can store both max value and its index.
int index = 0;
int max = scores[0];
for (int i = 1; i < scores.length; i++) {
if (scores[i] > max) {
index = i;
max = scores[i];
}
}
System.out.printf("Max Name: %s Max Score: %s", sNames[index], max);
we should do this in java way, or the Object Oriented way.
For that we will need a Student class.
public class Student implements Comparable<Student> {
private Integer score;
private String name;
public Student() {
super();
}
public Student(Integer score, String name) {
super();
this.score = score;
this.name = name;
}
public Integer getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int compareTo(Student o) {
return this.score.compareTo(o.getScore());
}
#Override
public String toString() {
return "Student [score=" + score + ", name=" + name + "]";
}
}
Then we can use this Student class anywhere and play around with the list of students as we want, like below.
public class Driver {
public static void main(String[] args) {
Student s1 = new Student(67, "Billy");
Student s2 = new Student(86, "Bobbi");
Student s3 = new Student(90, "Barbara");
Student s4 = new Student(20, "Beni");
Student s5 = new Student(55, "Baron");
Student s6 = new Student(98, "Becky");
Student s7 = new Student(90, "Ben");
List<Student> students = new ArrayList<>();
students.add(s1);
students.add(s2);
students.add(s3);
students.add(s4);
students.add(s5);
students.add(s6);
students.add(s7);
System.out.println("Minimum score student is :");
System.out.println(getMinScoreSudent(students));
System.out.println("\nMaximum score student is :");
System.out.println(getMaxScoreSudent(students));
System.out.println("\nAll Sudents :");
printStudentsInConsole(students);
}
public static Student getMinScoreSudent(List<Student> students) {
Collections.sort(students, Comparator.comparing(Student::getScore));
return students.get(0);
}
public static Student getMaxScoreSudent(List<Student> students) {
Collections.sort(students, Comparator.comparing(Student::getScore).reversed());
return students.get(0);
}
public static void printStudentsInConsole(List<Student> students) {
Collections.sort(students, Comparator.comparing(Student::getScore));
students.stream().forEach(student -> System.out.println(student));
}
This prints below message in console.
Minimum score student is :
Student [score=20, name=Beni]
Maximum score student is :
Student [score=98, name=Becky]
All Sudents :
Student [score=20, name=Beni]
Student [score=55, name=Baron]
Student [score=67, name=Billy]
Student [score=86, name=Bobbi]
Student [score=90, name=Barbara]
Student [score=90, name=Ben]
Student [score=98, name=Becky]

2D Array, best average calculator using HashMap

Problem Statement: I have a 2D array of strings containing student names and respective marks as below
String[][] scores = {{"Bob","85"},{"Mark","100"},{"Charles","63"},{"Mark","34"}};
I want to calculate the best average among all the students available, i.e with the above input the best average should be 85.
My Attempt:
I tried to solve this using HashMap as below.
public int bestAverageCalculator(String[][] scores) {
// This HashMap maps student name to their list of scores
Map<String,List<Integer>> scoreMap = new HashMap<String,List<Integer>>();
for(String[] score:scores) {
String name = score[0];
int currentScore =Integer.parseInt(score[1]);
if(scoreMap.containsKey(name)) {
List<Integer> scoreList = scoreMap.get(name);
scoreList.add(currentScore);
scoreMap.put(name, scoreList);
}
else {
List<Integer> scoreList = new ArrayList<Integer>();
scoreList.add(currentScore);
scoreMap.put(name, scoreList);
}
}
//scoreMap will be {Charles=[63], Bob=[85], Mark=[100, 34]}
//After Map is formed i am iterating though all the values and finding the best average as below
int bestAverage = 0;
for(List<Integer> value:scoreMap.values()) {
int sum = 0;
int count = 0;
for(int i:value) {
sum+=i;
count++;
}
int average = (int)Math.floor(sum/count);
if(average>bestAverage)
bestAverage = average;
}
return bestAverage;// returns 85
}
The implementation is correct and i am getting the answer as expected, but i was told the space complexity of the program is more and it can be achieved without using the List<Integer> for marks, i am not able to understand how average can be calculated on fly without storing list of marks.
Please suggest if any other methods can solve this other than HashMap.
Any help would be appreciated.
You could store for each student a constant amount of data :
the student's name
the sum of all the student's marks
the number of the student's marks
This will make the space complexity O(m) where m is the number of unique students (instead of your O(n) where n is the number of marks).
For example, you can have a Student class with these 3 properties (and store the data in a List<Student>), or you can have a Map<String,int[]> with the key being the student's name and the value being an array of two elements containing the sum of the marks and the number of marks.
You can construct this data while iterating over the input.
Now you can compute the average for each student and find the highest average.
Well for space saving you can store two numbers per person
avgSum and count and calculate average on the end.
I have implemented #Eran 's approach based on your code with a Map<String,int[]> with
key: student's name
value: an array of two elements [the sum of the scores, the number of scores]
public int bestAverageCalculator(String[][] scores) {
// This HashMap maps student name to their total scores and count in an int array format of [totalScores, count]
Map<String,int[]> scoreMap = new HashMap<String,int[]>();
for(String[] score:scores) {
String name = score[0];
int currentScore =Integer.parseInt(score[1]);
if(scoreMap.containsKey(name)) {
int[] scoreCount = scoreMap.get(name);
scoreCount[0] += currentScore;
scoreCount[1] ++;
scoreMap.put(name, scoreCount);
}
else {
int[] scoreCount = new int[]{currentScore, 1};
scoreMap.put(name, scoreCount);
}
}
int bestAverage = 0;
for(int[] value:scoreMap.values()) {
int average = (int)Math.floor(value[0]/value[1]);
if(average>bestAverage)
bestAverage = average;
}
return bestAverage;// returns 85
}
#Eran's idea but with Student class, at least for me it's much more clear
import java.util.*;
public class Main {
static String[][] scores = {{"Bob", "85"}, {"Mark", "100"}, {"Charles", "63"}, {"Mark", "34"}};
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
for (String[] score : scores) {
String name = score[0];
int currentScore = Integer.parseInt(score[1]);
Student student = findStudentByName(name, students);
if (student != null) {
student.setNumberOfScores(student.getNumberOfScores() + 1);
student.setSumOfScores(student.getSumOfScores() + currentScore);
} else {
student = new Student(name, 1, currentScore);
students.add(student);
}
}
findStudentWithBestAverage(students);
}
private static void findStudentWithBestAverage(List<Student> students) {
Student bestStudent = null;
int bestAverage = 0;
for (int i = 0; i < students.size(); i++) {
if ((students.get(i).getSumOfScores() / students.get(i).getNumberOfScores()) > bestAverage) {
bestStudent = students.get(i);
bestAverage = (students.get(i).getSumOfScores() / students.get(i).getNumberOfScores());
}
}
System.out.println(bestStudent + " with average: " + bestAverage);
}
private static Student findStudentByName(String name, List<Student> students) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getName().equals(name)) {
return students.get(i);
}
}
return null;
}
public static class Student {
private String name;
private int numberOfScores;
private int sumOfScores;
public Student(String name, int numberOfScores, int sumOfScores) {
this.name = name;
this.numberOfScores = numberOfScores;
this.sumOfScores = sumOfScores;
}
public String getName() {
return name;
}
public int getNumberOfScores() {
return numberOfScores;
}
public void setNumberOfScores(int numberOfScores) {
this.numberOfScores = numberOfScores;
}
public int getSumOfScores() {
return sumOfScores;
}
public void setSumOfScores(int sumOfScores) {
this.sumOfScores = sumOfScores;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return name.equals(student.name);
}
#Override
public int hashCode() {
return Objects.hash(name);
}
#Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", numberOfScores=" + numberOfScores +
", sumOfScores=" + sumOfScores +
'}';
}
}
}

Getting Java methods from one object and a constructor from another object

I have three class Homework that has my main(...), GradeArray, which has my methods, and StudentGrade, which has my constructor.
Currently , which is clearly wrong, I have in Homework:
GradeArray grades = new GradeArray();`
In GradeArray at the top I have StudentGrade[] ArrayGrades = new StudentGrade[size]; however this method did not give me both the contructor and the methods. I know I don't need three classes for this but my professor wants three class. How do I declare an array that has attributes from two classes so that I can get the methods from GradeArray and the constructor from StudentGrade?
Thank you for you time and help.
Here is all of my code
package homework1;
public class Homework1
{
public static int pubSize;
public static String pubCourseID;
public static void makeVarsPub(int maxSize, String courseID) //this is to makes the varibles public
{
pubSize = maxSize;
pubCourseID = courseID;
}
public int giveSize()
{
return pubSize;
}
public static void main(String[] args)
{
int maxSize = 100;
String courseID = "CS116";
//this is to makes the varibles public
makeVarsPub(maxSize, courseID);
StudentGrade grades = new StudentGrade();
grades.insert("Evans", 78, courseID);
grades.insert("Smith", 77, courseID);
grades.insert("Yee", 83, courseID);
grades.insert("Adams", 63, courseID);
grades.insert("Hashimoto", 91, courseID);
grades.insert("Stimson", 89, courseID);
grades.insert("Velasquez", 72, courseID);
grades.insert("Lamarque", 74, courseID);
grades.insert("Vang", 52, courseID);
grades.insert("Creswell", 88, courseID);
// print grade summary: course ID, average, how many A, B, C, D and Fs
System.out.println(grades);
String searchKey = "Stimson"; // search for item
String found = grades.find(searchKey);
if (found != null) {
System.out.print("Found ");
System.out.print(found);
}
else
System.out.println("Can't find " + searchKey);
// Find average and standard deviation
System.out.println("Grade Average: " + grades.avg());
System.out.println("Standard dev; " + grades.std());
// Show student grades sorted by name and sorted by grade
grades.reportGrades(); // sorted by name
grades.reportGradesSorted(); // sorted by grade
System.out.println("Deleting Smith, Yee, and Creswell");
grades.delete("Smith"); // delete 3 items
grades.delete("Yee");
grades.delete("Creswell");
System.out.println(grades); // display the course summary again
}//end of Main
}//end of homework1
package homework1;
class GradeArray
{
int nElems = 0; //keeping track of the number of entires in the array.
Homework1 homework1InfoCall = new Homework1(); //this is so I can get the information I need.
int size = homework1InfoCall.giveSize();
StudentGrade[] ArrayGrades = new StudentGrade[size];
public String ToString(String name, int score, String courseID)
{
String res = "Name: " + name + "\n";
res += "Score: " + score + "\n";
res += "CourseID " + courseID + "\n";
return res;
}
public String getName(int num) //returns name based on array location.
{
return ArrayGrades[num].name;
}
public double getScore(int num) //returns score based on array location.
{
return ArrayGrades[num].score;
}
public void insert(String name, double score, String courseID) //part of the insert method is going to be
//taken from lab one and modified to fit the need.
{
if(nElems == size){
System.out.println("Array is full");
System.out.println("Please delete an Item before trying to add more");
System.out.println("");
}
else{
ArrayGrades[nElems].name = name;
ArrayGrades[nElems].score = score;
ArrayGrades[nElems].courseID = courseID;
nElems++; // increment the number of elements
};
}
public void delete(String name) //code partly taken from lab1
{
int j;
for(j=0; j<nElems; j++) // look for it
if( name == ArrayGrades[j].name)
break;
if(j>nElems) // can't find it
{
System.out.println("Item not found");
}
else // found it
{
for(int k=j; k<nElems; k++) // move higher ones down
{
boolean go = true;
if ((k+2)>size)
go = false;
if(go)
ArrayGrades[k] = ArrayGrades[k+1];
}
nElems--; // decrement size
System.out.println("success");
}
}
public String find (String name){ //code partly taken from lab1
int j;
for(j=0; j<nElems; j++) // for each element,
if(ArrayGrades[j].name == name) // found item?
break; // exit loop before end
if(j == nElems) // gone to end?
return null; // yes, can't find it
else
return ArrayGrades[j].toString();
}
public double avg() //this is to get the average
{
double total = 0;
for(int j=0; j<nElems; j++)
total += ArrayGrades[j].score;
total /= nElems;
return total;
}
public double std() //this is to get the standard deviation. Information on Standard deviation derived from
//https://stackoverflow.com/questions/18390548/how-to-calculate-standard-deviation-using-java
{
double mean = 0; //this is to hold the mean
double newSum = 0;
for(int j=0; j < ArrayGrades.length; j++) //this is to get the mean.
mean =+ ArrayGrades[j].score;
for(int i=0; i < ArrayGrades.length; i++) //this is to get the new sum.
newSum =+ (ArrayGrades[i].score - mean);
mean = newSum/ArrayGrades.length; //this is to get the final answer for the mean.
return mean;
}
public StudentGrade[] reportGrades() //this is grade sorted by name
{
int in,out;
char compair; //this is for compairsons.
StudentGrade temp; //this is to hold the orginal variable.
//for the first letter cycle
for(out=1; out<ArrayGrades.length; out++)
{
temp = ArrayGrades[out];
compair= ArrayGrades[out].name.charAt(0);
in=out;
while(in>0 && ArrayGrades[in-1].name.charAt(0) > compair)
{
ArrayGrades[in] = ArrayGrades[in-1];
in--;
}
ArrayGrades[in]=temp;
}
//this is for the second run.
for(out=1; out<ArrayGrades.length; out++)
{
temp = ArrayGrades[out];
compair= ArrayGrades[out].name.charAt(1);
in=out;
while(in>0 && ArrayGrades[in-1].name.charAt(1) > compair)
{
ArrayGrades[in] = ArrayGrades[in-1];
in--;
}
ArrayGrades[in]=temp;
}
return ArrayGrades;
}
public StudentGrade[] reportGradesSorted() //this is grades sorted by grades.
//this is grabbed from lab2 and repurposed.
{
int in,out;
double temp;
for(out=1; out<ArrayGrades.length; out++)
{
temp=ArrayGrades[out].score;
in=out;
while(in>0 && ArrayGrades[in-1].score>=temp)
{
ArrayGrades[in]= ArrayGrades[in-1];
in--;
}
ArrayGrades[in].score=temp;
}
return ArrayGrades;
} //end of GradeArray
package homework1;
public class StudentGrade extends GradeArray
{
public String name;
double score;
public String courseID;
public void StudentGrade (String name, double score, String courseID) //this is the constructor
{
this.name = name;
this.score = score;
this.courseID = courseID;
}
}//end of StudentGrade class.
First, I feel #Alexandr has the best answer. Talk with your professor.
Your question doesn't make it quite clear what you need. However, it sounds like basic understanding of inheritance and class construction would get you going on the right path. Each of the 3 classes will have a constructor that is unique to that type. Each of the 3 classes will have methods and data (members) unique to those types.
Below is just a quick example of what I threw together. I have strong concerns that my answer is actually what your professor is looking for however--it is not an object model I would suggest--just an example.
public class Homework {
private String student;
public Homework(String name) {
student = name;
}
public String getStudent() {
return student;
}
}
public class StudentGrade extends Homework {
private String grade;
public StudentGrade(String grade, String name) {
super(name);
this.grade = grade;
}
public String getGrade() {
return grade;
}
}
public class HomeworkGrades {
public List<StudentGrade> getGrades() {
// this method isnt implemented but should
// be finished to return array of grades
}
}
Take a look and see if that helps you understand something about inheritance and class construction.
Hopefully you can infer a bit about inheritence (StudentGrade inherits -- in java extends -- from HomeWork) and class construction.
Thnx
Matt
I change the array creation in Homework1 to be StudentGrade grades = new StudentGrade(); and I added extends GradeArray to the StudentGrade class. it is now public class StudentGrade extends GradeArray.

Sorting the User input in Java

I am beginner in Java. I need help to proceed my code. Thanks in advance.
Question: Given a unsorted list of 5 athletes nominated for the coaching class, provide a way for the coach to search for the athlete name and provide grades. Finally print the list of athletes’ names with their grade in the sorted order of their names. Search for the athlete with highest grade.
package student;
import java.util.Scanner;
public class Atheletes {
String name;
static String grade,grade1,grade2,grade3,grade4;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of athelete1 and grade");
grade1 = in.nextLine();
Scanner ino = new Scanner(System.in);
System.out.println("Enter the name of athelete2 and grade");
grade2 = ino.nextLine();
Scanner ine = new Scanner(System.in);
System.out.println("Enter the name of athelete3and grade");
grade3 = ine.nextLine();
Scanner inp = new Scanner(System.in);
System.out.println("Enter the name of athelete4 and grade");
grade4 = inp.nextLine();
}
}
I have simplified your code and added comments as necessary.
// number of Athletes you want
Athlete[] eAthlete = new Athlete[5];
// Name of each athlete
String[] names = { "ss", "aa", "bb", "cc", "xx" };
// On each iteration, the name of the Athlete
// and his/her grade is set,
Scanner in = new Scanner(System.in);
for (int i = 0; i < eAthlete.length; i++) {
eAthlete[i] = new Athlete();
eAthlete[i].setName(names[i]);
System.out.println("Please enter Grade for: "
+ eAthlete[i].getName());
eAthlete[i].setGrade(in.nextLine());
}
in.close();
// Print all athletes with their grades,
System.out.println("Before Sorting");
for (Athlete s : eAthlete) {
System.out.println(s.getName() + " " + s.getGrade());
}
At this point, the grades and names are assigned to each athlete,
Output
Before Sorting
ss 123
aa 65465
bb 4654
cc .0231
xx 23123
Now we need to sort these Athletes based on their names.
We could have designed our own Comparator but since, you are not allowed to use Collections.sort, we would use rather poor approach i.e bubble sorting,
String tempStr;
for (int t=0; t<eAthlete.length-1; t++)
{
for (int i= 0; i < eAthlete.length - t -1; i++)
{
if(eAthlete[i+1].getName().compareTo(eAthlete[i].getName())<0)
{
tempStr = eAthlete[i].getName();
eAthlete[i].setName(eAthlete[i+1].getName());
eAthlete[i+1].setName(tempStr);
}
}
}
Printing the sorted athletes with their grades,
System.out.println("After Sorting");
for (Athelete s : eAthelete){
System.out.println(s.getName() + " " + s.getGrade());
}
Output:
After Sorting
aa 65465
bb 4654
cc .0231
ss 123
xx 23123
observe the names in above output.
here is your Athlete class,
class Athlete {
private String name;
private String grade;
public void setName(String name) {
this.name = name;
}
public void setGrade(String gr) {
grade = gr;
}
public String getGrade() {
return grade;
}
public String getName() {
return name;
}
}
Here is the complete code,
public class Main {
public static void main(String[] args) {
Athlete[] eAthlete = new Athlete[5];
String[] names = { "ss", "aa", "bb", "cc", "xx" };
Scanner in = new Scanner(System.in);
for (int i = 0; i < eAthlete.length; i++) {
eAthlete[i] = new Athlete();
eAthlete[i].setName(names[i]);
System.out.println("Please enter Grade for: "
+ eAthlete[i].getName());
eAthlete[i].setGrade(in.nextLine());
}
in.close();
// Print all athletes with their grades,
System.out.println("Before Sorting");
for (Athlete s : eAthlete) {
System.out.println(s.getName() + " " + s.getGrade());
}
String tempStr;
for (int t = 0; t < eAthlete.length - 1; t++) {
for (int i = 0; i < eAthlete.length - t - 1; i++) {
if (eAthlete[i + 1].getName().compareTo(eAthlete[i].getName()) < 0) {
tempStr = eAthlete[i].getName();
eAthlete[i].setName(eAthlete[i + 1].getName());
eAthlete[i + 1].setName(tempStr);
}
}
}
System.out.println("After Sorting");
for (Athlete s : eAthlete) {
System.out.println(s.getName() + " " + s.getGrade());
}
}
}
class Athlete {
private String name;
private String grade;
public void setName(String name) {
this.name = name;
}
public void setGrade(String gr) {
grade = gr;
}
public String getGrade() {
return grade;
}
public String getName() {
return name;
}
}
public class Athletes {
private String name;
private String grade;
public Athletes(String name, String grade) {
this.name = name;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
#Override
public String toString() {
return "Athletes [name=" + name + ", grade=" + grade + "]";
}
public static void main(String[] args) {
List<Athletes> lijst = new ArrayList<Athletes>();
lijst.add(new Athletes("bbb", "Grade1"));
lijst.add(new Athletes("ccc", "Grade2"));
lijst.add(new Athletes("aaa", "Grade3"));
lijst.add(new Athletes("ddd", "Grade4"));
Collections.sort(lijst, new Comparator<Athletes>() {
#Override
public int compare(Athletes o1, Athletes o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (Athletes athletes : lijst) {
System.out.println(athletes);
}
}
}
You may write your own comparator Class to sort the Athelete on basis of their names
public class AtheleteComparator implements Comparator
{
#override
public int compare(Atheletes first,Atheletes second)
{
return first.name.compareTo(second.name);
}
}
Then simply use
Collections.sort(List<Athelete>list,Your own Comparator's object)
To find out athelete with highest grade write another comparator which compares grades
then use
Collections.sort(arrayList,Comparator); // Sort the arraylist
arrayList.get(arrayList.size() - 1); //gets the last item, largest for an ascending sort
Ok, since you can use arrays and for loops but not collections:
public class Sorter(){
private int[] grades = {7, 6, 4, 10, 8};
private String[] names = {"John", "Erik", "Bob", "Frank", "Judy"};
public static void main(String args[]) {
new Sorter();
}
public Sorter(){
int[] tempGrades = {0, 0, 0, 0, 0};
String[] tempNames = {"", "", "", "", ""};
for (int x = 0; x < tempGrades.length; x++) {
if (grades[x] < tempGrades[1]) {
tempGrades[0] = grades[x];
tempNames[0] = names[x];
} else if (grades[x] < tempGrades[2]) {
tempGrades[0] = tempGrades[1];
tempGrades[1] = grades[x];
tempNames[0] = tempNames[1];
tempNames[1] = names[x];
} else if (grades[x] < tempGrades[3]) {
tempGrades[0] = tempGrades[1];
tempGrades[1] = tempGrades[2];
tempGrades[2] = grades[x];
tempNames[0] = tempNames[1];
tempNames[1] = tempNames[2];
tempNames[2] = names[x];
} else if (grades[x] < tempGrades[4]) {
tempGrades[0] = tempGrades[1];
tempGrades[1] = tempGrades[2];
tempGrades[2] = tempGrades[3];
tempGrades[3] = grades[x];
tempNames[0] = tempNames[1];
tempNames[1] = tempNames[2];
tempNames[2] = tempNames[3];
tempNames[3] = names[x];
} else {
tempGrades[0] = tempGrades[1];
tempGrades[1] = tempGrades[2];
tempGrades[2] = tempGrades[3];
tempGrades[3] = tempGrades[4];
tempGrades[4] = grades[x];
tempNames[0] = tempNames[1];
tempNames[1] = tempNames[2];
tempNames[2] = tempNames[3];
tempNames[3] = tempNames[4];
tempNames[4] = names[x];
}
}
grades = tempGrades;
names = tempNames;
for (int x = 0; x < grades.length; x++) {
System.out.println(tempNames[x] + " " + tempGrades[x]);
}
}
}
just for the future:
you can use an ArrayList<Athlete> where Athlete is a class that accepts (String name, int grade) as constructor paramaters and sorts athletes by grade by implementing its own comparator or you can use a LinkedHashMap<Integer, String> that sorts values by Key<Integer>.
Note: Class names with plural like Athletes are best used for Singleton classes that only implement static methods and variables. Always name classes by function (in this case sorting), AthleteSorter is also viable.

Categories