Java: how to return an Array? - java

this is the code, from what I understand, it is suppose to work.
Also when I debug my program, it seems that the array is being filled with the objects that the same method is creating.
But still, when I try to print it, it shows me "null" back agian, like the "return" does not work.
Why is it happening?
public class Course {
String courseName;
String teacherName;
int gradeAv;
static int counter;
static int maxNumOfStudents;
Student studentsArray[] = new Student[5];
int numOfStudents = studentsArray.length;
public Course() {
}
public Course(String courseName) {
this();
this.courseName = courseName;
}
public Course(String courseName, String teacherName) {
this(courseName);
this.courseName = courseName;
this.teacherName = teacherName;
}
public Student[] addStudent(String name, int age, int grade) {
for (int i = 0; i < 5; i++) {
studentsArray[i] = new Student(name, age, grade);
age += 10;
grade += 10;
}
return studentsArray;
}
public void printStudentArray(Student studentArray[]) {
studentArray = this.studentsArray;
for (int i = 0; i < studentsArray.length; i++) {
System.out.println(studentsArray[i]);
}
}
public int gradeAv() {
for (int i = 0; i < studentsArray.length; i++) {
int temp = 0;
if (studentsArray[i].grade > temp) {
gradeAv = temp;
System.out.println(gradeAv);
}
}
return gradeAv;
}
public void printCourse() {
System.out.println("Course: ");
System.out.println("Course Name: " + courseName + ". "
+ "Teacher's Name: " + teacherName + ". "
+ "Number Of Students: " + numOfStudents + ". ");
}
}
This is my main class:
public class MainClass {
public static void main(String[] args) {
Student stud = new Student();
Course cour = new Course("Java", "Ronni");
stud.addStudent("Joe", 23, 100);
stud.printStudent();
System.out.println();
stud.printCourse();
System.out.println();
cour.printStudentArray(cour.studentsArray);
System.out.println();
// cour.gradeAv();
}
}

in
Student stud = new Student();
Course cour = new Course("Java", "Ronni");
stud.addStudent("Joe", 23, 100);
stud.addStudent("Joe", 23, 100); will not add any students to your course. stud is an instance of a completely different class, Student, and the implementation of Student is not in the code you've posted.
call the addStudent method of cour instead of the one for stud
cour.addStudent("Joe", 23, 100);
instead
I would also like to add that there are a lot of curious elements to your code, some of which people have brought up in the comments. It would be tedious to list them all. I'd take a look-through, just to make sure you're not doing redundant things.

Try this for example:
Course class:
import java.util.ArrayList;
import java.util.List;
public class Course {
private List<Student> students = new ArrayList<Student>();
private String teacherName;
private String subjectName;
public Course(String subjectName, String teacherName) {
this.subjectName = subjectName;
this.teacherName = teacherName;
}
public void addStudent(Student student) {
students.add(student);
}
public float getAverageGrade() {
float grade = 0;
for (Student student : students) {
grade += student.getGrade();
}
return grade / students.size();
}
public void printCourse() {
System.out.println("Course "+subjectName+" taught by "+teacherName);
System.out.println("Students:");
printStudents();
System.out.println("Aberage grade: "+getAverageGrade());
}
public void printStudents() {
for (Student student : students) {
System.out.println(student.getName()+"\t age "+student.getAge()+" \t grade "+student.getGrade());
}
}
}
Student class:
public class Student {
private String name;
private int age;
private int grade;
public Student(String name, int age, int grade) {
this.grade = grade;
this.age = age;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}

Related

Getting Top Student and calculating average score

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];

How do I get a string user input and increase value by +1 using Java ArrayList?

I have the following code and I want to ask the user after an name that's already stored in the Arraylist and increase that (dogs) age by +1.
Here's the most important (I guess) part of the code. This is the Register Class.
import java.util.Scanner;
import java.util.ArrayList;
public class Register {
private Scanner keyboard = new Scanner(System.in);
private ArrayList<Dog> dogs = new ArrayList<>();
private String readString() {
return keyboard.nextLine();
}
public int readInt() {
int i = keyboard.nextInt();
keyboard.nextLine();
return i;
}
public double readDouble() {
double d = keyboard.nextDouble();
keyboard.nextLine();
return d;
}
public void registrateDog(){
System.out.println("Dogs name: ");
String name = readString();
System.out.println("Dogs breed: ");
String breed = readString();
System.out.println("Dogs age: ");
int age = readInt();
System.out.println("Dogs weight: ");
double weight = readDouble();
Dog newDog = new Dog(name, breed, age, weight);
dogs.add(newDog);
System.out.println(newDog.toString() + " is added");
}
public void increaseAge(){ //Here's the problem
System.out.print("Enter dog who has aged: ");
String newDogAge = readString();
int addAge = 1;
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
addAge = (dogs.get(i).getAge());
dogs.set(i, dogs.get(i));
System.out.println("Dog " + newDogAge + " is now " + addAge);
return;
}
}
private void exitProgram(){
System.out.println("Goodbye!");
keyboard.close();
}
private void run(){
setUp();
runCommandLoop();
exitProgram();
}
public static void main(String[] args){
new Register().run();
//setUp();
}
}
And
public class Dog {
private String name;
private String breed;
private int age;
private double weight;
private double tailLenght;
private String tax = "tax";
public Dog(String name, String breed, int age, double weight){
this.name = name;
this.breed = breed;
this.age = age;
this.weight = weight;
if (breed.equals(tax)) {
this.tailLenght = 3.7;
} else {
this.tailLenght = (age*weight) / 10;
}
}
public String getName(){
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBreed(){
return breed;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
public int newAge(){
return age = age + 1;
}
public double getWeight(){
return weight;
}
public double getTailLenght(){
return tailLenght;
}
public String toString()
{ return String.format("%s, %s, %d years old, %.1f kg, "
+ "tail lenght %.1f cm", name, breed, age, weight, tailLenght);
}
}
So in this code you're finding the Dog by its name. Which is great.
public void increaseAge() {
System.out.print("Enter dog who has aged: ");
String newDogAge = readString();
int addAge = 1;
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
addAge = (dogs.get(i).getAge());
dogs.set(i, dogs.get(i));
System.out.println("Dog " + newDogAge + " is now " + addAge);
return;
}
}
Inside of your Dog class you have a method which returns the age, what you want to do is modify it to:
public int newAge(){
this.age++; // This will take the current age of the dog and add one to it
}
Now going back to the increaseAge() method you want to modify the for loop to look like:
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
dogs.get(i).newAge(); // This will update the Dogs age by 1 year
System.out.println("Dog " + dogs.get(i).getName() + " is now " + dogs.get(i).getAge());
return;
}
Where are you incrementing the age ? Call the newAge() method as you have defined in the Dog class.`
Dog dog = dogs.get(i);
dog.setAge(dog.newAge());
dogs.set(i,dog);`
We've fetched the particular dog who's details matched. Then we incremented it's age and set it back in the list at that position.

Java Objects and Classes - something wrong with my code?

I'm having issues trying to figure out the problem with my code. Basically, the program is supposed to be a GPA calculator.
The first part:
import java.io.*;
import java.util.ArrayList;
public class Student {
// Data
private String name;
private int student_id;
private double gpa;
private ArrayList<Integer> grades;
private int num_courses;
// Methods
// Constructor Method
public Student() {
name = "";
student_id = 0;
gpa = 0.0;
grades = new ArrayList<Integer>();
}
// Accessor Methods (getters and setters)
public void setGrade(int g) {
grades.add(g);
calcGPA();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStudent_id() {
return student_id;
}
public void setStudent_id(int student_id) {
this.student_id = student_id;
}
public double getGPA() {
return gpa;
}
public void setGpa(double gpa) {
this.gpa = gpa;
}
public int getNum_courses() {
return num_courses;
}
public void setNum_courses(int num_courses) {
this.num_courses = num_courses;
}
// Functional Methods
public void calcGPA() {
int sum_grades = 0;
for (int i=0; i<this.grades.size(); i++) {
sum_grades = sum_grades * this.grades.get(i);
}
gpa = sum_grades/this.grades.size();
}
public void displayGrades() {
for (int i=0; i<this.grades.size(); i++) {
System.out.println("Grade in course " + i + ": " + this.grades.get(i));
}
}
}
and the second class:
import java.io.*;
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student(); //Object creation/instantiation
s1.setName("John Rodgers");
s1.setStudent_id(111);
s1.setGrade(3);
s1.setGrade(4);
s1.setGrade(3);
System.out.println("Student " + s1.getName() + "\'s GPA: " + s1.getGPA());
Student s2 = new Student();
s2.setName("Jenny Marshall");
s2.setStudent_id(333);
s2.setGrade(4);
s2.setGrade(4);
s2.setGrade(3);
s2.setGrade(4);
s2.setGrade(3);
System.out.println("Student " + s2.getName() + "\'s GPA: " + s2.getGPA());
}
}
The output shows as:
Student John Rodgers's GPA: 0.0
Student Jenny Marshall's GPA: 0.0
The GPA is supposed to be calculated but it appears as 0.0.
Your calcGPA() logic is incorrect (you are doing a product with 0), rather you should sum all grades as shown below:
public void calcGPA(){
int sum_grades = 0;
for(int i=0; i<this.grades.size(); i++){
sum_grades = sum_grades + this.grades.get(i);//sum the grades
}
gpa = sum_grades/this.grades.size();
}

Find higest value among objects created in a class

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

Create an array and try to declare inside loop found error ArrayIndexOutOfBoundsException

package sortpractice;
public class Employee implements Comparable<Employee> {
int id;
String name;
int age;
long salary;
public Employee(int id, String name, int age, long salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
public long getSalary() {
return this.salary;
}
public String toString() {
return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary="
+ this.salary + "]";
}
#Override
public int compareTo(Employee emp) {
return (this.id - emp.id);
}
}
package sortpractice;
import java.util.Arrays;
public class JavaObjectSorting {
int[] id = {3, 1, 2};
String[] name = {"A", "B", "C"};
int[] age = {10, 20, 30};
long[] salary = {100, 200, 300};
public JavaObjectSorting() {
for (int i = 0; i < id.length; i++) {
Employee[] test = new Employee[i];
System.out.println(i);
test[i] = new Employee(id[i], name[i], age[i], salary[i]);
}
}
public static void main(String args[]) {
JavaObjectSorting j = new JavaObjectSorting();
}
}
put following line outside the for loop
Employee[] test = new Employee[id.length];
Now you code will like this:
for (int i = 0; i < id.length; i++) {
test[i] = new Employee(id[i], name[i], age[i], salary[i]);
}
for i = 0 .. it will be
Employee[] test = new Employee[0];
so declare and initiate the array before the loop
Employee[] test = new Employee[id.lenght];
for (int i = 0; i < id.length; i++) {
System.out.println(i);
test[i] = new Employee(id[i], name[i], age[i], salary[i]);
}

Categories

Resources