As part of the curriculum at my school, we are working on some CodeHS Java.
There is one problem that I'm stuck on:
Taking our Student and Classroom example from earlier, you should fill in the method getMostImprovedStudent, as well as the method getExamRange. The most improved student is the one with the largest exam score range.
To compute the exam score range, you must subtract the minimum exam score from the maximum exam score.
For example, if the exam scores were 90, 75, and 84, the range would be 90 - 75 = 15.
This is the Student class which I added my method getExamRange().
import java.util.*;
public class Student
{
private static final int NUM_EXAMS = 4;
private String firstName;
private String lastName;
private int gradeLevel;
private double gpa;
private int[] exams;
private int numExamsTaken;
public static int[] examRange = new int[Classroom.numStudentsAdded];
private int i = 0;
/**
* This is a constructor. A constructor is a method
* that creates an object -- it creates an instance
* of the class. What that means is it takes the input
* parameters and sets the instance variables (or fields)
* to the proper values.
*
* Check out StudentTester.java for an example of how to use
* this constructor.
*/
public Student(String fName, String lName, int grade)
{
firstName = fName;
lastName = lName;
gradeLevel = grade;
exams = new int[NUM_EXAMS];
numExamsTaken = 0;
}
public int getExamRange()
{
Arrays.sort(exams);
examRange[i] = exams[exams.length-1] - exams[0];
i++;
return exams[exams.length-1] - exams[0];
}
public String getName()
{
return firstName + " " + lastName;
}
public void addExamScore(int score)
{
exams[numExamsTaken] = score;
numExamsTaken++;
}
// This is a setter method to set the GPA for the Student.
public void setGPA(double theGPA)
{
gpa = theGPA;
}
/**
* This is a toString for the Student class. It returns a String
* representation of the object, which includes the fields
* in that object.
*/
public String toString()
{
return firstName + " " + lastName + " is in grade: " + gradeLevel;
}
}
And this is the Classroom class in which I added the method getMostImprovedStudent().
import java.util.*;
public class Classroom
{
Student[] students;
static int numStudentsAdded;
public Classroom(int numStudents)
{
students = new Student[numStudents];
numStudentsAdded = 0;
}
public Student getMostImprovedStudent()
{
Arrays.sort(Student.examRange);
//return Student.examRange[0];
}
public void addStudent(Student s)
{
students[numStudentsAdded] = s;
numStudentsAdded++;
}
public void printStudents()
{
for(int i = 0; i < numStudentsAdded; i++)
{
System.out.println(students[i]);
}
}
}
I can get the exam Range by sorting the exams array then subtracting the smallest from the biggest, but once I do this, how do I find the student with the biggest exam range, and return it?
The way you would do this is looping through students, and have a variable to hold the biggest difference in score, and the most improved student:
public Student getMostImprovedStudent()
{
Student mostImproved = students[0];
int biggest = student[i].getExamRange();
for(int i = 1; i < students.length; i++) {
if(students[i].getExamRange() > biggest) {
mostImproved = students[i];
biggest = students[i].getExamRange();
}
}
return mostImproved;
}
However Java 8+ we can do:
public Student getMostImprovedStudent()
{
return Arrays.stream(students)
.max(Comparator.comparing(Student::getExamRange))
.get();
}
Which is assuming that students is not empty
As I explained in the comment above you can do it this way:
public Student getMostImprovedStudent() {
Student maxRangeStudent = null;
int maxRange = 0;
for (Student student: students) {
int curExamRange = student.getExamRange();
if (curExamRange > maxRange){
maxRangeStudent = student;
maxRange = curExamRange;
}
}
return maxRangeStudent;
}
Related
I have an assignment that requires me to create a method called getExamRange that looks at an array which includes the exam scores of several students, takes the lowest and highest scores, and subtracts the minimum exam score from the maximum exam score. I also have to create a getMostImprovedStudent which run the getExamRange method on an array of Students and returns the student with the highest exam range. I'm having trouble getting the correct results when the code is run. What is causing this problem?
Here is the code for the Student.java class:
import java.util.*;
public class Student
{
private static final int NUM_EXAMS = 4;
private String firstName;
private String lastName;
private int gradeLevel;
private double gpa;
private int[] exams;
private int numExamsTaken;
/**
* This is a constructor. A constructor is a method
* that creates an object -- it creates an instance
* of the class. What that means is it takes the input
* parameters and sets the instance variables (or fields)
* to the proper values.
*
* Check out StudentTester.java for an example of how to use
* this constructor.
*/
public Student(String fName, String lName, int grade)
{
firstName = fName;
lastName = lName;
gradeLevel = grade;
exams = new int[NUM_EXAMS];
numExamsTaken = 0;
}
public int getExamRange()
{
Arrays.sort(exams);
int examScore1 = exams[0];
int examScore2 = 0;
int lastPos = 0;
for(int i = 0; i < exams.length - 1; i++)
{
lastPos++;
}
examScore2 = exams[lastPos];
return examScore2 - examScore1;
}
public String getName()
{
return firstName + " " + lastName;
}
public void addExamScore(int score)
{
exams[numExamsTaken] = score;
numExamsTaken++;
}
// This is a setter method to set the GPA for the Student.
public void setGPA(double theGPA)
{
gpa = theGPA;
}
/**
* This is a toString for the Student class. It returns a String
* representation of the object, which includes the fields
* in that object.
*/
public String toString()
{
return firstName + " " + lastName + " is in grade: " + gradeLevel;
}
}
and here is the code for the Classroom.java class:
public class Classroom
{
Student[] students;
int numStudentsAdded;
public Classroom(int numStudents)
{
students = new Student[numStudents];
numStudentsAdded = 0;
}
public Student getMostImprovedStudent()
{
int highestScore = 0;
int score = 0;
int location = 0;
int finalLocation = 0;
for(Student s: students)
{
score = s.getExamRange();
location++;
if(score > highestScore)
{
highestScore = score;
finalLocation = location;
}
}
return students[finalLocation - 1];
}
public void addStudent(Student s)
{
students[numStudentsAdded] = s;
numStudentsAdded++;
}
public void printStudents()
{
for(int i = 0; i < numStudentsAdded; i++)
{
System.out.println(students[i]);
}
}
}
Here are the directions for the assignment which state what the methods are supposed to do:
Taking our Student and Classroom example from earlier, you should fill in the method getMostImprovedStudent, as well as the method getExamRange. The most improved student is the one with the largest exam score range.
To compute the exam score range, you must subtract the minimum exam score from the maximum exam score.
For example, if the exam scores were 90, 75, and 84, the range would be 90 - 75 = 15.
Firstly let us look at the getExamRange function
public int getExamRange(){
if(exams == null ||exams.length == 0){
return 0;
}
int min = exams[0];
int max = exams[0];
for (int i : exams
) {
if(i<min){
min=i;
}
if(i>max){
max=i;
}
}
return max - min;
}
and now on getMostImprovedStudent
public Student getMostImprovedStudent()
{
if(students == null ||students[0] == null || students.length=0){
return null;
}
int highestScore = students[0].getExamRange();
int score = 0;
Student mostImprovedStudent = students[0]
for(int i=0;i<students.length;i++)
{
if(students[i]!=null){
score = students[i].getExamRange();
if(score > highestScore)
{
highestScore = score;
mostImprovedStudent = students[i];
}
}
}
return mostImprovedStudent;
}
I am writing a program to find and display the student with the highest GPA, as well as the student with the lowest GPA out of a class with 4 attributes (first name, last name, age, GPA).
The output for my code results in "build successful," but the parsing error still shows up and there isn't the proper output information.
public class app
{
public static void main(String args[ ])
{
student st1 = new student("Rebecca", "Collins", 22, 3.3);
student st2 = new student("Alex", "White", 19, 2.8);
student st3 = new student("Jordan", "Anderson", 22, 3.1);
student[ ] studentArray = new student[3];
studentArray[0] = st1;
studentArray[1] = st2;
studentArray[2] = st3;
var maxStudent = studentArray[0];
// Start at 1 because we assumed the first student in the array
// has the current max.
//
for (int i = 1; i < studentArray.length; i++)
{
// If the current student has a GPA higher than the student
// with the current max, make the current student the student
// with the current max.
//
if(studentArray[i].gpa > maxStudent.getGpa())
{
boolean max = false;
boolean min;
min = false;
for (student studentArray1 : studentArray) {
boolean gpa = false;
}
System.out.print("The highest GPA is: "+max);
System.out.println();
System.out.print("The lowest GPA is: "+min);
System.out.println();
System.out.println("Name: "+ studentArray[i].firstName + " "+ studentArray[i].lastName);
System.out.println("Age: "+ studentArray[i].age);
System.out.println("GPA: "+ studentArray[i].gpa);
}
}
public class student
{
//class variables
public String firstName;
public String lastName;
public int age;
public double gpa;
public int max = 0;
public int min = 0;
//constructor method
student(String a, String b, int c, double d)
{
firstName = a;
lastName = b;
age = c;
gpa = d;
}
student(String a, String b, int c, double d, int e, int f)
{
firstName = a;
lastName = b;
age = c;
gpa = d;
min = e;
max = f;
}
//a method that returns the student's complete name
String getInfo()
{
return getFirstName() +" " + getLastName() +" " + getMax();
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String fn)
{
firstName = fn;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String ln)
{
lastName = ln;
}
public int getAge()
{
return age;
}
public void setAge(int x)
{
age = x;
}
public double getGpa()
{
return gpa;
}
public void getGpa(double g)
{
gpa = g;
}
public int getMax()
{
return max;
}
public void getMax(int e)
{
max = e;
}
public int getMin()
{
return min;
}
public void getMin(int f)
{
min = f;
}
}
I would appreciate any insight that addresses the error and solutions for what I can do to make this code work properly.
There are a number of (possible) issues with your posted code; you appear to be using an inner student class; your braces don't match up and your indentation doesn't seem to be consistent, and the var keyword doesn't exist in versions of Java prior to 10 (and we have no knowledge of your installed JDK or configured project compiler level). Your student(s) shouldn't have individual min and max fields.
There is some debate about the merits of a class with all public fields; but any possible advantage to that is negated when you also implement getters and setters for all of them.
You need two loops; one to find the min and max, one to display the student(s). Java naming conventions should be respected (class names start with a capital letter). And you have a getGpa(double) that should be a setter.
Fixing all of that, it might look something like
public class App {
public static class Student {
private String firstName;
private String lastName;
private int age;
private double gpa;
public Student(String a, String b, int c, double d) {
firstName = a;
lastName = b;
age = c;
gpa = d;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String fn) {
firstName = fn;
}
public String getLastName() {
return lastName;
}
public void setLastName(String ln) {
lastName = ln;
}
public int getAge() {
return age;
}
public void setAge(int x) {
age = x;
}
public double getGpa() {
return gpa;
}
public void setGpa(double g) {
gpa = g;
}
}
public static void main(String[] args) throws Exception {
Student st1 = new Student("Rebecca", "Collins", 22, 3.3);
Student st2 = new Student("Alex", "White", 19, 2.8);
Student st3 = new Student("Jordan", "Anderson", 22, 3.1);
Student[] studentArray = { st1, st2, st3 };
Student maxStudent = studentArray[0];
Student minStudent = studentArray[0];
for (int i = 1; i < studentArray.length; i++) {
if (studentArray[i].getGpa() > maxStudent.getGpa()) {
maxStudent = studentArray[i];
}
if (studentArray[i].getGpa() < minStudent.getGpa()) {
minStudent = studentArray[i];
}
}
System.out.printf("The highest GPA is: %.1f%n", maxStudent.getGpa());
System.out.printf("The lowest GPA is: %.1f%n", minStudent.getGpa());
for (Student s : studentArray) {
System.out.printf("Name: %s %s%n", s.getFirstName(), s.getLastName());
System.out.printf("Age: %d%n", s.getAge());
System.out.printf("GPA: %.1f%n", s.getGpa());
}
}
}
which I ran; producing
The highest GPA is: 3.3
The lowest GPA is: 2.8
Name: Rebecca Collins
Age: 22
GPA: 3.3
Name: Alex White
Age: 19
GPA: 2.8
Name: Jordan Anderson
Age: 22
GPA: 3.1
And, if you're using Java 8+, you could simplify the main code with DoubleSummaryStatistics by streaming the Student(s), mapping to the gpa value and then collecting the statistics. Like,
public static void main(String[] args) throws Exception {
Student st1 = new Student("Rebecca", "Collins", 22, 3.3);
Student st2 = new Student("Alex", "White", 19, 2.8);
Student st3 = new Student("Jordan", "Anderson", 22, 3.1);
Student[] studentArray = { st1, st2, st3 };
DoubleSummaryStatistics dss = Arrays.stream(studentArray).mapToDouble(Student::getGpa).summaryStatistics();
System.out.printf("The highest GPA is: %.1f%n", dss.getMax());
System.out.printf("The lowest GPA is: %.1f%n", dss.getMin());
Arrays.stream(studentArray).map(s -> String.format("Name: %s %s%nAge: %d%nGPA: %.1f", //
s.getFirstName(), s.getLastName(), s.getAge(), s.getGpa())).forEach(System.out::println);
}
I am a novice java student. I have a project for a java class where I am to write a Golfer class, Score class and a tester for the Golfer class to test all methods. The specific problems I am having is :
When I call the addScore method, the method overwrites the old data instead of adding to the existing. I need to get the program to add the scores in the array in addition to the previous score.
The findScore method is private and used in the public method getScore, however, when I run the program, I get the null value regardless of the parameter in the call. I need to return the index of an array based on the date entered.
The following is excerpts from the code and not the entire program.
public class Golfer {
/**String representing the golfer's name*/
private String name;
/**String representing the golf course where the golfer's hadicap is kept*/
private String homeCourse;
/**Unique integer that identifies every golfer*/
private int idNum;
/**Array storing all the golfer's scores*/
private Score[] scores;
public static int nextIDNum;
/**Default constructor, sets all instance field to a default value. Creates Array.
*/
public Golfer() {
name = "";
homeCourse = "";
scores = new Score[0];
nextIDNum = 1000;
}
/**Constructor sets name and homeCourse from parameters and uses the static variable nextIDNum to retrieve the next available ID number. Creates Array.
*/
public Golfer(String golferName, String home) {
setName(golferName);
setHomeCourse(home);
setNextIDNum(nextIDNum);
scores = new Score[10];
}
/**Creates a Score object from the parameters that represent the course, course rating, course slope, date and score. Adds the newly created Score object to the Array of Scores.
#param golfCourse A String representing the golf course name
#param rating A double representing the golf course rating
#param slope An int representing the golf course slope
#param scoreDate A String representing the date the course was played
#param score An int representing what was scored on the course
*/
public void addScore(String golfCourse, double rating, int slope, String scoreDate, int score) {
Score[] golfScores = new Score[scores.length + 1];
for (int i = 0; i < scores.length; i++) {
golfScores[i] = scores[i];
}
golfScores[golfScores.length - 1] = new Score(golfCourse, rating, slope, scoreDate, score);
scores = golfScores;
}
/**Deletes a score from the Array based on score date, Assumes only one score per day.
#param golfDate A string representing the date of the golf score
#return true if score found and deleted,
#return false if score not found.
*/
public boolean deleteScore (String golfDate) {
for (int i = 0; i < scores.length; i++) {
if (findScore(golfDate) > 0) {
scores[i] = null;
}
return true;
}
return false;
}
/**Returns a score object based on the score date. If not found returns null
#param golfDate The date of the golf score
#return Scores[i] The score on the parameterized date
#return null A null value if the score was not found.
*/
public Score getScore(String golfDate) {
for (int i = 0; i < scores.length; i++) {
if (findScore(golfDate) > 0) {
return scores[i];
}
}
return null;
}
/**Given a parameter representing the score's date, finds the score on a given date and returns the Array index of a score. Return constant NOTFOUND if not found.
#param golfDate A string representing the date of the score
#return i An array index representing the score
#return NOTFOUND A constant set to -1 if the score isn't found
*/
private int findScore(String golfDate) {
final int NOTFOUND = -1;
for (int i = 0; i < scores.length; i++) {
if (scores[i].equals(golfDate)) {
return i;
}
}
return NOTFOUND;
}
}
The score class:
public class Score {
private String courseName;
private int score;
private String date;
private double courseRating;
private int courseSlope;
public Score(String course, double rating, int slope, String golfDate, int scr) {
setCourseName(course);
setScore(scr);
setDate(golfDate);
setCourseRating(rating);
setCourseSlope(slope);
}
public Score() {
courseName = "";
score = 0;
date = "";
courseRating = 0.0;
courseSlope = 0;
}
public void setCourseName(String course) {
courseName = course;
}
public String getCourseName() {
return courseName;
}
public void setScore(int golfScore) {
if ((golfScore < 40) && (golfScore > 200)) {
golfScore = 9999;
System.out.println("Error: golf score must be between 40 and 200.");
}
score = golfScore;
}
public int getScore() {
return score;
}
public void setDate(String golfDate) {
date = golfDate;
}
public String getDate() {
return date;
}
public void setCourseRating(double rating) {
if ((rating < 60) && (rating > 80)) {
rating = 9999;
System.out.println("Error: the course rating must be between 60 and 80.");
}
courseRating = rating;
}
public double getCourseRating() {
return courseRating;
}
public void setCourseSlope(int slope) {
if ((slope < 55) && (slope > 155)) {
slope = 9999;
System.out.println("Error: The course slope must be between 55 and 155.");
}
courseSlope = slope;
}
}
The tester class:
public class GolferTester {
public static void main (String []args) {
String course1 = "Augusta National";
String course2 = "Bayhill CC";
String course3 = "TPC Sawgrass";
String player1 = "Sam Snead";
String player2 = "Arnold Palmer";
String player3 = "Jack Nicklaus";
int score1 = 66;
int score2 = 201;
int score3 = 72;
int slope1 = 60;
int slope2 = 156;
int slope3 = 77;
double rating1 = 65.2;
double rating2 = 81.8;
double rating3 = 70.9;
String date1 = "01/01/2017";
String date2 = "06/01/2016";
String date3 = "12/22/2016";
Golfer golfer1 = new Golfer(player1, course1);
Golfer golfer2 = new Golfer(player2, course2);
Score s1 = new Score(course1, rating1, slope1, date1, score1);
Score s2 = new Score(course2, rating2, slope2, date2, score2);
s1.setScore(score1);
s1.setDate(date1);
s1.setCourseRating(rating1);
s1.setCourseSlope(slope1);
s1.setCourseName(course1);
s2.setScore(score3);
s2.setDate(date3);
s2.setCourseRating(rating3);
s2.setCourseSlope(slope3);
s2.setCourseName(course3);
golfer1.addScore(s1.getCourseName(), s1.getCourseRating(), s1.getCourseSlope(), s1.getDate(), s1.getScore());
golfer2.addScore(s2.getCourseName(), s2.getCourseRating(), s2.getCourseSlope(), s2.getDate(), s2.getScore());
System.out.println(golfer1);
System.out.println("");
System.out.println(golfer2);
System.out.println("");
s1.setScore(score2);
s1.setCourseRating(rating2);
s1.setCourseSlope(slope2);
golfer1.addScore(s1.getCourseName(), s1.getCourseRating(), s1.getCourseSlope(), s1.getDate(), s1.getScore());
System.out.println(golfer1);
deleteScore(s1.getDate());
System.out.println(s1.getDate());
}
}
Any help would be appreacited
Don't use an array for a list of elements that you know will grow/shrink. Use ArrayList, which has add()
Your getScore method is returning null always
i already have the athelete class and i just dont know how to go about the rest of the problem ive been trying to do things that havent work at all but heres what i have for now. im still a beginner this is my first semester taking java so i may not understand some of the things you guys will add so if u can please explain.
This is what they are asking for me to do.
Add a static method to the class which takes an array of Athletes as its argument, and returns the total number of medals won by all athletes stored in the array. test in method.
package homework;
import java.util.Arrays;
public class Athlete {
private String name; // the name of the athlete
private String sport; // the sport the athlete does
private int numMedals; // the number of medals that the athlete has won
// constructor
public Athlete(String n, String s, int num) {
name = n;
sport = s;
numMedals = num;
}
// getters and setters for all instance variables
// (also called accessors and mutators)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSport() {
return sport;
}
public void setSport(String sport) {
this.sport = sport;
}
public int getNumMedals() {
return numMedals;
}
public void setNumMedals(int numMedals) {
this.numMedals = numMedals;
}
/* Returns a String with information about the athlete.
*/
public String toString() {
return name + " does " + sport + " and has won " + numMedals + " medal(s).";
}
public static void AthMedals(int[][]numMedals){
for(int i = 0; i < numMedals.length;i++){
int total = 0;
for(int j = 0; j < numMedals.length; i++);
total = numMedals.getNumMedals();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Athlete SA = new Athlete("Socrates","Baseball",5);
Athlete CC = new Athlete("Cesar","Baseball",3);
Athlete JA = new Athlete("Juan","Soccer",2);
System.out.println(SA);
System.out.println(CC);
System.out.println(JA);
System.out.println("SA has " +SA.getNumMedals()+ " medals.");
}
}
}
The assignment is to write a method like
public static int sumOfAllMedals(Athlete[] all)
which returns all[0].numMedals + all[1].numMedals + ... + all[n].numMedals.
I assume AthMedals is your attempt at doing this, but it's in fact only consuming processing power while not doing anything.
I'm not gonna do your homework for you, but here's a hint:
public static int sumOfAllMedals(Athlete[] all)
{
int total = 0;
// For every Athlete in `all`, add the number of medals (s)he's won
// Should be four lines at most ;)
return total;
}
The static method have to iterate the array and add each medals to a final return variable.
static public int totalMedals(Athlete[] athelte) {
int totalMedals = 0;
for(int i=0;i<athelte.length;i++) {
totalMedals += athelte[i].numMedals;
}
return totalMeadls;
}
I wrote a program that is supposed to read in records from a file and enter them into an array of a Student class. I then need to sort them by name.
import java.io.*;
import java.util.Scanner;
public class StudentTest
{
public static void main(String[] args)
{
String name;
String address;
String major;
double gpa;
int classLevel;
int college;
String blank;
String idNumber;
Scanner fileIn = null;
try
{
fileIn = new Scanner (new FileInputStream("student.dat"));
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
System.exit(0);
}
Student[] aStudent = new Student[15];
int index = 0;
for (index=0; index <= 15; index++)
{
while (fileIn.hasNext())
{
name = fileIn.nextLine();
address = fileIn.nextLine();
major = fileIn.nextLine();
gpa = fileIn.nextDouble();
classLevel = fileIn.nextInt();
college = fileIn.nextInt();
fileIn.nextLine();
idNumber = fileIn.nextLine();
aStudent[index] = new Student(name, address, major, gpa, classLevel, college, idNumber);
aStudent[index].Display();
}
}
Student temp = null;
for (int pass = 0; pass < (index-1); pass++)
{
for (int c = 0; c < (index - 1); c++)
{
if (aStudent[].getName() > aStudent[c+1].getName())
{
temp = aStudent[];
aStudent[]=aStudent[+1];
aStudent[+1]=temp;
}
}
}
}
}
import java.util.Scanner;
public class Student
{
private String name;
private String address;
private String major;
private double gpa;
private int classLevel;
private int college;
private String idNumber;
Scanner keyboard = new Scanner(System.in);
public Student(String name, String address, String major, double gpa, int classLevel, int coll, String idNum)
{
this.name = name;
this.address = address;
this.gpa = gpa;
this.major = major;
this.classLevel = classLevel;
this.college = coll;
this.idNumber = idNum;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public String getMajor()
{
return major;
}
public double getGPA()
{
return gpa;
}
public int getClassLevel()
{
return classLevel;
}
public int getCollege()
{
return college;
}
public String getID()
{
return idNumber;
}
public void setAddress(String address)
{
}
public void setMajor(String maj)
{
}
public void setCollege(int coll)
{
}
public void Display()
{
System.out.println("Name: "+getName());
System.out.println("Address: "+getAddress());
System.out.println("Major: " + getMajor());
System.out.println("GPA: "+getGPA()+" Class Level: "+getClassLevel()+" College: "+getCollege());
System.out.println("ID: "+getID());
System.out.println("===============================");
}
}
I wrote the sort the way my proffessor described it in class, but I am still getting errors that "the > operator is undefined for the argument type(s) java.laungage.String"
Any help would be greatly appreciated.
thanks
Edit:
I used Ashan's suggestion and now it looks like this.
for (int pass = 0; pass < (index-1); pass++)
{
for (int c = 0; c < (index - 1); c++)
{
if (aStudent[c].getName().compareTo(aStudent[c+1].getName()) > 0)
{
temp = aStudent[c];
aStudent[c]=aStudent[+1];
aStudent[+1]=temp;
That cleared up that error. However, I am now getting a NullPointerException.
You cannot compare strings using operator such as < , > . To compare strings there is a methodd provided in String class called compareTo. This method compares two strings lexicographically.
compareTo returns
0 incase both the strings are lexicographically equal
-1 if the calling string is lexicographically smaller than the input string
1 if the calling string is lexicographically larger than the input stirng
You can replace the following condition
if (aStudent[].getName() > aStudent[c+1].getName())
using compareTo method as:
if (aStudent[].getName().compareTo(aStudent[c+1].getName()) > 0)
I think error is because you cannot compare how big is the name or how small it is. Making a bubble search to sort names by alphabetical order, you need to check their first characters ASCII. Which is a pretty easy thing to do. I am not good at Java, but C++. So algorithms are same ;) Good luck ;)
You may want to use compareTo() of String. > and < are used for int, float numbers, characters and etc., not for objects like strings. If objects support compare operations, it must implement the Comparable interface, in which you will define the compareTo() method.
This method will return -1 if it is less than the other, 0 if they are equal and 1 if it is greater than the other object.