2D Array, best average calculator using HashMap - java

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 +
'}';
}
}
}

Related

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]

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.

Java getTopStudent and getAverageScore using arrays

I've been studying code on my own, and I got a problem that I do not know how to answer.
I am given a student and classroom class, and from those two I need to be able to create a method for getTopStudent, as well as thegetAverageScore.
**Edit: All of the code was given except for the two methods, I needed to create those 2. The thing is that I'm not sure if what I'm doing is correct.
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 Student(String fName, String lName, int grade)
{
firstName = fName;
lastName = lName;
gradeLevel = grade;
exams = new int[NUM_EXAMS];
numExamsTaken = 0;
}
public double getAverageScore() //this is the method that I need to, but I'm not sure if it is even correct.
{
int z=0;
for(int i =0; i<exams.length; i++)
{
z+=exams[i];
}
return z/(double) numExamsTaken;
}
public String getName()
{
return firstName + " " + lastName;
}
public void addExamScore(int score)
{
exams[numExamsTaken] = score;
numExamsTaken++;
}
public void setGPA(double theGPA)
{
gpa = theGPA;
}
public String toString()
{
return firstName + " " + lastName + " is in grade: " + gradeLevel;
}
}
public class Classroom
{
Student[] students;
int numStudentsAdded;
public Classroom(int numStudents)
{
students = new Student[numStudents];
numStudentsAdded = 0;
}
public Student getTopStudent() //this is the other method I need to create
{
int x=0;
int y=0;
for(int i =0; i<numStudentsAdded; i++)
{
if(x<students.getAverageScore())
{
x=students.getAverage();
y++;
}
}
return students[y];
}
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 have something down for each of them but it isn't running. I don't fully understand arrays yet, but this is apparently a beginner code using arrays. If anyone could help with what I need to do and tell me how arrays work, much would be appreciated.
getAverageScore() is a method of Student. But students is not a Student object, it's an array of Student objects. (And getAverage(), which you call inside the for loop, isn't a method at all.) An array is a separate object that contains other objects or primitives (like ints) in it. So students.getAverageScore() is not going to compile, because students doesn't have that method, each of its members (student[0], student[1], etc.) has it.
Try replacing the getTopStudent method with something like this:
public Student getTopStudent() //this is the other method I need to create
{
int x=0; //this will contain the highest average
int y=0; //this will be the index in the array of the highest scoring student
for(int i =0; i<numStudentsAdded; i++)
{
int currentAverage = students[i].getAverageScore(); //run the getAverageScore() on the current student
if(x<currentAverage) // compare it to the previous high average
{
x=currentAverage; // replace x with new high average
y=i; //replace the index of the highest scoring student with current index i
}
}
return students[y]; // so if the fifth student had the highest score, y would be 4
}
So you are having trouble int the method public Student getTopStudent()
public Student getTopStudent() //this is the other method I need to create
{
double x= students[0].getAverageScore();
int y = 0;
for(int i=1;i<students.length;i++){
if(x<students[i].getAverageScore()) {
x = students[i].getAverageScore();
y =i;
}
}
return students[y];
}
See if this helps

How to calculate student's average grade using HashMap?

In the Student class, I need to add a method to put a new course into the student's course collection and a method that calculates and returns the student's average grade. I keep getting "NaN" as a result when I try to calculate the student's average grade. Would appreciate any help. Thanks.
Below is my source code for the Student class.
import java.util.HashMap;
import java.util.Set;
public class Student extends Member
{
// instance variables of class Student
private HashMap<String, Double> courses;
public Student()
{
super();
courses = new HashMap<String, Double>();
}
/**
* Constructor
* #param firstName
* #param lastName
* #param emailAddress
* #param bcitId
*/
public Student(String firstName, String lastName, String emailAddress, String bcitId)
{
super(firstName, lastName, emailAddress, bcitId);
courses = new HashMap<String, Double>();
}
public void addCourse(String course, Double grade)
{
if(!courses.isEmpty()) {
courses.put(course, grade);
}
}
public Double getAverageGrade()
{
Double averageGrade = 0.0;
int counter = 0;
if(!courses.isEmpty()){
Set<String> course = courses.keySet();
for(String grade : course){
averageGrade += courses.get(grade);
counter++;
}
}
return (averageGrade /= counter);
}
}
Your method
public void addCourse(String course, Double grade)
{
if(!courses.isEmpty()) {
courses.put(course, grade);
}
}
looks funny to me. Do you intend to only add a course if there is already at least one course in the map? This way, how will the first course enter the map?
I think you tried to check for the map to exist, but that would be done differently, namely:
if (courses == null){
...
}
About the division problem look at the other answer from Saposhiente. I would only repeat it...
int counter = 0;
return (averageGrade /= counter);
NaN indicates division by zero, among other things. Counter was never incremented because no courses were added; see luksch's answer for why. Also, since you will never reference averageGrade again, you can simply use
return averageGrade / counter;
which is slightly more efficient.
The only way it's going to return NaN is when the courses.isEmpty() returns true as the couter will not be incremented and you will divide by 0.
Also you could improve your cycle by using getValues()
public Double getAverageGrade()
{
Double averageGrade = 0.0;
int counter = 0;
if(!courses.isEmpty()){
for(Double grade : courses.getValues()){
averageGrade += grade
counter++;
}
} else {
return -1; // or some value that says that are no grades yet
}
return (averageGrade /= counter);
}
Here you go with a simple HashMap technique , refer the Below code for Caluclating
average and find the Beststudent from it,Understand it well , I might help you
Thanks...
import java.util.*;
public class QueQue {
public static float getAverage(HashMap<String, ArrayList<Integer>> hm, String name) {
ArrayList<Integer> scores;
scores = hm.get(name);
if (scores == null) {
System.out.println("NOT found");
}
int sum = 0;
for (int x : scores) {
sum += x;
}
return (float) sum / scores.size();
}
// The best students from these Key-Value Pair
public static String getBestStudent(HashMap<String, ArrayList<Integer>> hm) {
double max = 0;
String beststudent = null;
for (Map.Entry<String, ArrayList<Integer>> x : hm.entrySet()) {
String name = x.getKey();
double average = getAverage(hm, name);
if (average > max) {
max = average;
beststudent = name;
}
}
return beststudent;
}
public static void main(String[] args) {
HashMap<String, ArrayList<Integer>> hm = new HashMap<>();
hm.put("Peter", new ArrayList<>());
hm.get("Peter").add(10);
hm.get("Peter").add(10);
hm.get("Peter").add(10);
hm.put("Nancy", new ArrayList<>());
hm.get("Nancy").add(7);
hm.get("Nancy").add(8);
hm.get("Nancy").add(8);
hm.put("Lily", new ArrayList<>());
hm.get("Lily").add(9);
hm.get("Lily").add(9);
hm.get("Lily").add(8);
System.out.println("Find the average of the Peter");
float num = getAverage(hm, "Peter");
System.out.println(num);
String name = getBestStudent(hm);
System.out.println(name);
}
}

trouble with array lists

I am doing a project and instead of using an array, I figured an array list would be better. I know I need to declare the array list and its methods, but I am not too sure where to go from there. Any suggestions? Here's code...
public class Student {
private String name;
private int[] tests;
public Student() {
this("");
}
public Student(String nm) {
this(nm, 3);
}
public Student(String nm, int n) {
name = nm;
tests = new int[n];
for (int i = 0; i < tests.length; i++) {
tests[i] = 0;
}
}
public Student(String nm, int[] t) {
tests = new int[t.length];
}
public Student(Student s) {
this(s.name, s.tests);
}
public int getNumberOfTests() {
return tests.length;
}
public void setName(String nm) {
name = nm;
}
public String getName() {
return name;
}
public void setScore(int i, int score) {
tests[i - 1] = score;
}
public int getScore(int i) {
return tests[i - 1];
}
public int getAverage() {
int sum = 0;
for (int score : tests) {
sum += score;
}
return sum / tests.length;
}
public int getHighScore() {
int highScore = 0;
for (int score : tests) {
highScore = Math.max(highScore, score);
}
return highScore;
}
public String toString() {
String str = "Name: " + name + "\n";
for (int i = 0; i < tests.length; i++) {
str += "test " + (i + 1) + ": " + tests[i] + "\n";
}
str += "Average: " + getAverage();
return str;
}
public String validateData() {
if (name.equals("")) {
return "SORRY: name required";
}
for (int score : tests) {
if (score < 0 || score > 100) {
String str = "SORRY: must have " + 0 + " <= test score <= " + 100;
return str;
}
}
return null;
}
}
I figured an array list would be better
Maybe. Maybe not. It depends. Does it look like you would get a benefit in using one based on the ArrayList API?
If your "list" never changes size, and you don't need to find things in it, then an array is just as good.
I know I need to declare the array list and its methods, but I am not
too sure where to go from there
You need to create a reference to an instance of an ArrayList. That's as simple as
List<Integer> myList = new ArrayList<Integer>();
in your class declaration. You don't need to "declare its methods". When you have a reference to an object, you can invoke its methods.
To use an ArrayList, you just need to declare and instantiate it:
// <SomeObject> tells Java what kind of things go in the ArrayList
ArrayList<SomeObject> aDescriptiveNameHere = new ArrayList<SomeObject>();
// This is also valid, since an ArrayList is also a List
List<SomeObject> list = new ArrayList<SomeObject>();
Then you can add things with the add() method:
// Please don't name your list "list"
list.add(new Thing(1));
list.add(new Thing(2));
You can get something by index (like you would with someArray[index]) as:
list.get(index);
// For example
Thing t = list.get(5);
You probably also need the size().
See the JavaDocs for more info.
All of the operations you're using are mirrored in the ArrayList API. One thing that's worth noting is that you cannot declare an ArrayList of primitive types, but for each of the primitive types there exists an Object that is the boxed version of the primative.
The boxed version of int is Integer, so you have
ArrayList<Integer> myList = new ArrayList<Integer>();
From there, you need to look up the methods you would need to use in order to manipulate the array. For example, if you want to add the number 42 to the end of the array, you would say
myList.add(42);
The ArrayList API is located here.
I think it could be better to use the stl vector instead make your own arrays
I tried to change the array to arraylist.
Reply if this doesn't compile correctly.
import java.util.ArrayList;
public class Student {
private String name;
// private int[] tests;
private ArrayList<Integer> tests;
public Student() {
this("");
}
public Student(String nm) {
// this(nm, 3);
name = nm;
}
/*
* public Student(String nm, int n) { name = nm; tests = new int[n]; for
* (int i = 0; i < tests.length; i++) { tests[i] = 0; } }
*/
/*
* public Student(String nm, int[] t) { tests = new int[t.length]; }
*/
public Student(Student s) {
this(s.name, s.tests);
}
public Student(String name2, ArrayList<Integer> tests2) {
name = name2;
tests = tests2;
}
public int getNumberOfTests() {
return tests.size();
}
public void setName(String nm) {
name = nm;
}
public String getName() {
return name;
}
// public void setScore(int i, int score) {
// tests[i - 1] = score;
public void setScore(int score) {
tests.add(score);
}
public int getScore(int i) {
// return tests[i - 1];
return tests.get(i - 1);
}
public int getAverage() {
int sum = 0;
for (int score : tests) {
sum += score;
}
// return sum / tests.length;
return sum / tests.size();
}
public int getHighScore() {
int highScore = 0;
for (int score : tests) {
highScore = Math.max(highScore, score);
}
return highScore;
}
public String toString() {
String str = "Name: " + name + "\n";
for (int i = 0; i < tests.size(); i++) {
str += "test " + (i + 1) + ": " + tests.get(i) + "\n";
}
str += "Average: " + getAverage();
return str;
}
public String validateData() {
if (name.equals("")) {
return "SORRY: name required";
}
for (int score : tests) {
if (score < 0 || score > 100) {
String str = "SORRY: must have " + 0 + " <= test score <= "
+ 100;
return str;
}
}
return null;
}
public ArrayList<Integer> getTests() {
return tests;
}
public void setTests(ArrayList<Integer> tests) {
this.tests = tests;
}
}

Categories