Create gets and sets methods:
getStudentName() and setstudentName()
getStudentNumber() and setStudentNumber()
I am confused on what to put in the public void printGrades() and printAverage()
import java.util.Scanner;
public class studentGrader
{
Scanner input = new Scanner(System.in);
private String studentName;
private String studentNumber;
private String[] testNames;
private int[] testGrades;
private int currentTestPointer;
private int maxTestCount = 10;
private int averageGrade;
private int testScore;
public studentGrader(String studentNameL,String studentNumberL)
{
studentName = studentNameL;
studentNumber = studentNumberL;
testNames = new String[maxTestCount];
testGrades = new int[maxTestCount];
currentTestPointer = 0;
averageGrade = 0;
}
public void addTest(String testName, int testScore)
{
testNames[currentTestPointer] = testName;
}
public void printGrades()
{
}
public void printAverage()
{
}
}
//Most Getters are very simple.
//The goal is to simply return some variable that is privately stored in a class
//Notice that the variable "studentName" is of type "String" and the method is returning a type "String"
public String getStudentName() {
return studentName;
}
//Most Setters are the same as getters, except they set the variable instead
//This method takes in a parameter(in this case "name") and then sets the desired variable to given parameter
public void setstudentName(String name) {
studentName = name;
}
The getStudentNumber and setStudentNumber are the same and I'll leave that left undone as a mental exercise.
//This is an example of how to print something
public void printAverage() {
//There may be additional logic in here to determine the correct average grade
system.out.print(averageGrade);
}
There are some rules from Java code style (that not flow to error, but they are used by everyone) along with some JVM defaults:
Class name should be in camel-case: class studentGrader - class StudentGrader
Scanner class is used to work with inbound data (console, files, ets); this is not a data holder. Should be removed from the class and used as local variable in method.
In constructor (usually), same name for local properties and method parameters should be used. To get access to the local properties, do use this: this.studentName = studentName
Arrays testNames and testGrades are objects with know size. So you should declare it in the class definition and make it final (reference is final, but not array's content): private final String[] testNames = new String[10]; and private final int[] testGrades = new int[10];
Class local parameters are initialized to the default values. For int it is a 0. So no need to do it in the constructor for currentTestPointer and averageGrade
void addTest(String testName, int testScore), in your current increment currentTestPointer and check for arrays out of bound (not more than 10) (I think, it is better to use Map)
averageGrade should be double (I think): private double averageGrade;``
Finally, your class could look like this:
public class StudentGrader {
private static final int MAX_TEST_AMOUNT = 10;
private String studentName;
private String studentNumber;
private final String[] testNames = new String[MAX_TEST_AMOUNT];
private final int[] testGrades = new int[MAX_TEST_AMOUNT];
private int currentTestPointer;
private double averageGrade;
private int testScore;
public StudentGrader(String studentName, String studentNumber) {
this.studentName = studentName;
this.studentNumber = studentNumber;
}
public void addTest(String testName, int testScore) {
if (currentTestPointer < MAX_TEST_AMOUNT) {
testNames[currentTestPointer] = testName;
testGrades[currentTestPointer] = testScore;
currentTestPointer++;
}
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(String studentNumber) {
this.studentNumber = studentNumber;
}
public void printGrades() {
// <testName>: <testGrade>
for (int i = 0; i < currentTestPointer; i++)
System.out.println(testNames[i] + ": " + testGrades[i]);
}
public void printAverage() {
averageGrade = 0;
if (currentTestPointer > 0) {
for (int i = 0; i < currentTestPointer; i++)
averageGrade += testGrades[i];
averageGrade /= currentTestPointer;
}
System.out.println(averageGrade);
}
}
Related
We are given the Java class Student, class Randomizer, and class Classroom.
We were told to fill in the method for getTopStudent and getAverageScore.
Below I have included the classes for Student, Classroom, and ClassroomTester.
The problem: when I run it, the compiler errors.
And I don't get why it's wrong...I did not forget a semicolon and I am not sure what they meant by "illegal start of expression"
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()
{
int sum = 0;
for(int i = 0; i < exams.length;i++)
{
sum+=exams[i];
}
return (double)sum/numExamsTaken;
}
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;
}
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];
public Student getTopStudent()
{
double max = students[0].getAverageScore();
String topstudent = students[0].getName();
for (int i = 0; i < students.length; i++)
{
if (students[i].getAverageScore() > max)
{
max = students[i].getAverageScore();
topstudent = students[i];
}
}
return topstudent;
}
public void addStudent(Student s)
{
students[numStudentsAdded] = s;
numStudentsAdded++;
}
public void printStudents()
{
for(int i = 0; i < numStudentsAdded; i++)
{
System.out.println(students[i]);
}
}
}
public class ClassroomTester extends ConsoleProgram
{
public void run()
{
Classroom c = new Classroom(2);
Student ada = new Student("Ada", "Lovelace", 12);
ada.addExamScore(44);
ada.addExamScore(65);
ada.addExamScore(77);
Student alan = new Student("Alan", "Turing", 11);
alan.addExamScore(38);
alan.addExamScore(24);
alan.addExamScore(31);
// add students to classroom
c.addStudent(ada);
c.addStudent(alan);
c.printStudents();
Student topStudent = c.getTopStudent();
System.out.println(topStudent);
}
}
Change the constructor of Classroom to
public Classroom(int numStudents)
{
students = new Student[numStudents];
}
You are missing the closing brace } on the constructor of Classroom.
You are missing a closing {
public Classroom(int numStudents)
{
students = new Student[numStudents];
I have 3 classes, Movie which is used to add Movie objects to an in MovieDatabase but it keeps printing null.
When I add 2 Movies its like the first Movie is erased and it prints null instead. Also is there a way to check if the position in the array is empty and not print if it is empty?
Here is my Movie class
public class Movie {
private String name;
private String director;
private double fileSize;
private int duration;
private int moviecount;
public Movie()
{
name = null;
director = "";
fileSize = 0;
duration = 0;
}
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
public void setDirector(String newDirector)
{
director = newDirector;
}
public String getDirector()
{
return director;
}
public void setfileSize(double newfileSize)
{
fileSize = newfileSize;
}
public double getfileSize()
{
return fileSize;
}
public void setDuration(int newDuration)
{
duration = newDuration;
}
public int getDuration()
{
return duration;
}
and here my MovieDatabase class:
public class MovieDatabase
{
private Movie[] mov;
private int i;
public int count=0;
public MovieDatabase()
{
mov = new Movie[4];
i=0;
}
public void addData(String name, String director, double fileSize, int duration)
{
for(int i=0; i<4; i++)
mov[i] = new Movie();
setData(mov[i],name,director,fileSize,duration);
i++;
count++;
}
private void setData(Movie m,String name, String director, double fileSize, int duration)
{
mov[i].setName(name);
mov[i].setDirector(director);
mov[i].setfileSize(fileSize);
mov[i].setDuration(duration);
}
public void printNames()
{
for (int i = 0; i < mov.length; i++)
{
System.out.println(mov[i].getName());
}
}
}
import java.util.*;
public class Interface {
Scanner console = new Scanner(System.in);
MovieDatabase m = new MovieDatabase();
private void run()
{
int option;
do{
System.out.print("Add Movie(0), Delete Movie(2),Show Movies(3),Movie Count(4) \n");
option = console.nextInt();
switch(option)
{
case 0: addMovie();
break;
case 3: printMovies();
break;
}
}
while(option!=9);
}
public static void main(String[] args){
Interface intFace = new Interface();
intFace.run();
}
public void addMovie()
{
String name, director;
double fileSize;
int duration;
System.out.println("Movie Name: ");
name = console.next();
System.out.println("Movie Director: ");
director = console.next();
System.out.println("Movie File Size: ");
fileSize = console.nextDouble();
System.out.println("Movie Duration: ");
duration = console.nextInt();
System.out.print("Movie Added!");
m.addData(name,director,fileSize,duration);
}
public void printMovies()
{
m.printNames();
}
}
I tried to include only the relevant parts but majority of what I have done so far is relevant.
The problem is in these lines
....
public void addData(String name, String director, double fileSize, int duration)
{
for(int i=0; i<4; i++)
mov[i] = new Movie();
...
Each and every time you're adding a new data, you're erasing all previous records by assigning new movie object to every element in array. This erases all previous data.
You should instead move these 2 lines in MovieDatabase constructor. Or a better option would be to initialize them when you're setting data.
...
public void addData(String name, String director, double fileSize, int duration)
{
setData(mov[i],name,director,fileSize,duration);
i++;
count++;
}
private void setData(Movie m,String name, String director, double fileSize, int duration)
{
mov[i] = new Movie(); //++ edit
mov[i].setName(name);
mov[i].setDirector(director);
mov[i].setfileSize(fileSize);
mov[i].setDuration(duration);
}
...
Also is there a way to check if the position in the array is empty and not print if it is empty?
You can create a method in Movie class which checks whether this movie object is empty or not and returns appropriate result.
public class Movie {
...
...
public boolean isEmpty() {
if(
this.name.isEmpty() &&
this.director &&
this.fileSize == 0 &&
this.duration == 0 &&
this.moviecount == 0
)
return true;
else
return false;
}
...
...
}
Now you can check whether this movie object is empty or not using:
if(mov[i].isEmpty()) {
//empty movie object
...
}
In setData you always set the value of mov[0]. The class member i will never change (loop variable hides it). You do not use the parameter m to set the data.
Change your setData to
m.setName(name);
m.setDirector(director);
m.setfileSize(fileSize);
m.setDuration(duration);
I have an ArrayList of String named "info" and each string holds the information about an instance of my class Student.
I try converting the Arraylist into an array and then parsing it using split method.
String[] Stringinfo = new String[info.size()];
Stringinfo = info.toArray(Stringinfo);
after I parse each line I try to make a new object in my for loop and adding it to the Students ArrayList. What happens is that every time I create this new object Student, the other objects which were added to Students ArrayList before, are all changed to this new object.
String[] temp;
for(int i = 1; i < LineCount + 1 ; i++)
{
temp = Stringinfo[i].split(" ");
Student s = new Student(Integer.parseInt(temp[0]), Integer.parseInt(temp[1]), Integer.parseInt(temp[2]), Integer.parseInt(temp[3]), Integer.parseInt(temp[4]));
Students.add(s);
}
I tried printing Students in different points and everthing is alright until the new object is created.
At any time all the objects have the same attribute values as the last object created.
this is the Student class constructor:
public Student(int certif, int class_id, int ave, int i, int a)
{
certification_num = certif;
class_id = class;
average_point = ave;
student_id = i;
age = a;
}
I searched a lot but couldn't find an answer. Sorry if the answer is obvious I am new to Java.
Any help would be appreciated.
Thanks in advance.
Edit:
public class Student{
public Student(){}
public Student(int certif, int class, int ave, int i, int a)
{
certification_num = certif;
class_id = class;
average_point = ave;
student_id = i;
age = a;
}
public static int get_certification_num(){
return certification_num;
}
public static int get_class_id(){
return class_id;
}
public static int get_average_point(){
return average_point;
}
public static int get_id(){
return student_id;
}
public static int get_age(){
return age;
}
private static int certification_num;
private static int class_id;
private static int age;
private static int node_id;
private static int student_id;
}
Take the word static out of your Student class.
static means "one of these for all Students". But every student should have a different age, id etc., so those fields (and associated methods) should not be static.
Static members means that the member belong to the class and not to the object and thus your members keeps on changing.
My guess is your members are static, so try to define your Student class like this:
public class Student {
private int certification_num;
private int class_id;
private int average_point;
private int student_id;
private int age;
public Student(int certif, int clazz, int ave, int i, int a)
{
this.certification_num = certif;
this.class_id = clazz;
this.average_point = ave;
this.student_id = i;
this.age = a;
}
}
First of all I advice you to change your Student class as follow:
public class Student
{
private int certification_num;
private int class_id;
private int average_point;
private int student_id;
private int age;
public int getCertification_num() {
return this.certification_num;
}
// Do this for all variables
public void setCertification_num(int certif) {
this.certification_num = certif;
}
// Do this for all variables
}
After that you can easy use your Student class. Also in other situations, when you don't have or need all information.
Fill your Array:
ArrayList<Student> students = new ArrayList<Student>();
for(int i = 1; i < LineCount + 1 ; i++)
{
String[] temp;
temp = Stringinfo[i].split(" ");
Student s = new Student();
s.setCertification_num(Integer.parseInt(temp[0]);
//Do for all other fields
Students.add(s);
}
Can anybody explain how I get the highest value from all the objects I have created in my main class?
In this example I have created 2 students objects in my main class and added some course names and grades.
I have made 2 static arrays to store the information from the different objects but it doesn't return the object with the highest grade.
How do I store the highest grade from the student objects created?
public class CMate {
private static String[] studentName = new String[2];
private static int[][] gradeAssigned = new int[2][3];
private static int higGrade = 0;
private String name;
private int cpr;
private String[] courseName = new String[3];
private int[] grade = new int[3];
private int numberOfCourse;
private int numberOfGrades;
private static int counter = 0;
CMate(String name, int cpr) {
// building constructor
System.out.println("Creating object nr " + counter);
this.name = name;
this.cpr = cpr;
// insert name into array
studentName[counter] = name;
for (int i = 0; i < numberOfCourse; i++) {
gradeAssigned[counter][i] = grade[i];
}
counter++;
}
public void addcourseName(String nameOfCourse) {
courseName[numberOfCourse] = nameOfCourse;
numberOfCourse++;
}
public void addGrade(int gradeNr) {
grade[numberOfGrades] = gradeNr;
numberOfGrades++;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCpr() {
return cpr;
}
public void setCpr(int cpr) {
this.cpr = cpr;
}
public String[] getCourseName() {
return courseName;
}
public void setCourseName(String[] courseName) {
this.courseName = courseName;
}
public int[] getGrade() {
return grade;
}
public void setGrade(int[] grade) {
this.grade = grade;
}
public String toString() {
String studentInfo = "";
System.out.println("------------------------------\n student " + name + " CPR " + cpr);
for (int i = 0; i < numberOfCourse; i++) {
studentInfo += " Course " + courseName[i] + "Grade " + grade[i];
}
return studentInfo;
}
public double averageGrade() {
double total = 0;
for (int i = 0; i < numberOfGrades; i++) {
total += grade[i];
}
return (total / numberOfGrades);
}
public void higestGrade() {
for (int i = 0; i < studentName.length; i++) {
if (grade[i] > higGrade) {
higGrade = grade[i];
}
}
}
public void higestObjectGrade() {
System.out.println(higGrade);
}
}
I don't fully understand your code, but here's a simplified version, including a static field to keep all students, and a static function to return the highest grade:
class Student {
public final static List<Student> allCreatedStudents = new ArrayList<Student>();
String name;
int[] grades = new int[3];
public Student(String name){
this.name = name;
allCreatedStudents.add(this); // Every time a student is created, he is recorded in the static list
}
public void setGrade(int grade, int index){
this.grades[index] = grade;
}
public static int getHighestGrade(){
int highestGrade = 0;
for(Student s : allCreatedStudents){ // Loop through all students
for(int i=0; i<s.grades.length; i++){ // Loop through all grades
if(s.grades[i]>highestGrade)
highestGrade = s.grades[i];
}
}
return highestGrade;
}
}
I need to create a method with a default constructor, which sets name to an empty string and sets both credits and contactHours to zero. How to do it? Thanks, Pieter.
Methods don't have constructors... classes do. For example:
public class Dummy
{
private int credits;
private int contactHours;
private String name;
public Dummy()
{
name = "";
credits = 0;
contactHours = 0;
}
// More stuff here, e.g. property accessors
}
You don't really have to set credits or contactHours, as the int type defaults to 0 for fields anyway.
You're likely to want at least one constructor which takes initial values - in which case your parameterless one can delegate to that:
public class Dummy
{
private String name;
private int credits;
private int contactHours;
public Dummy()
{
this("", 0, 0);
}
public Dummy(String name, int credits, int contactHours)
{
this.name = name;
this.credits = credits;
this.contactHours = contactHours;
}
// More stuff here, e.g. property accessors
}
public class Test {
private String name;
private int credits;
private int contactHours;
public Test {
this( "", 0, 0);
}
public Test (String name, int credits, int contactHours) {
this.name = name;
this.credits = credits;
this.contactHours = contactHours;
}
// more code here
}
public class Bibabu{
private String name;
private int credits;
private int contactHours;
public Bibabu(){
name = ""; // you could also write this.name and so on...
credits = 0;
contactHours= 0;
}
// more code here
}
You don't need a constructor:
public class Dummy
{
private int credits = 0;
private int contactHours=0;
private String name="";
/*
public Dummy()
{
name = "";
credits = 0;
contactHours = 0;
}
*/
// More stuff here, e.g. property accessors
}
//constructor
public Account(int id, double balance, Person owner){
this.id = id;
this.balance = balance;
this.owner = owner;