Can somebody help me with one little problem. I want to set for example 3 lectures to 1 student, but when i try this i can't set lectures.
student.setStudentLecture(lecture);
student.setStudentLecture(lecture1);
public class Student {
private Lecture[] lecture;
public void setStudentLecture(Lecture[] lecture) {
this.lecture = lecture;
}
public Lecture[] getStudentLecture() {
return lecture;
}
}
You are using Array of Lecture objects and overwriting the same array with two different array references. Hence, it is not working. Use the below code:
public class Student {
private Lecture[] lecture;
public void setStudentLecture(Lecture[] lecture) {
this.lecture = lecture;
}
public Lecture[] getStudentLecture() {
return lecture;
}
public static void main(String[] args) {
Student student = new Student();
Lecture[] lectures = new Lecture[3];
lectures[0] = new Lecture("Physics");
lectures[1] = new Lecture("Mathematics");
lectures[2] = new Lecture("Chemistry");
student.setStudentLecture(lectures);
Lecture[] lectures1 = student.getStudentLecture();
for (int i = 0; i <lectures1.length; ++i) {
System.out.println(lectures1[i].getName());
}
}
}
public class Lecture {
private String name;
public Lecture(String name) {
this.name = name;
}
public String getName(){
return name;
}
}
As you setter is also array, you can create the Array of Lecture and set it to Student.
sample:-
Student student = new Student();
Lecture lecture = new Lecture();
Lecture lecture1 = new Lecture();
Lecture[] lectureArr = new Lecture[]{lecture, lecture1};
student.setStudentLecture(lectureArr);
And also you have studentLecture as array, then why you want to assign different array twice, you can combine both array and assign it.
Related
So I need help with this part of JAVA in my COP class OOP programming.
First is that I need to change the addStudent to static method but the code will not run because the this.student is not static which makes no sense because it already private static
import java.util.Arrays;
public class InitializerDemo {
public static final int MAX_STUDENTS = 10;
private static Student[] students;
private Instructor instructor;
private static int numStudents = 0;
// default constructor
public InitializerDemo() {
}
// instructor mutator
public void setInstructor(Instructor instructor) {
this.instructor = instructor;
}
// add a student, increment the count
//This PART!!! HELP
public static void addStudent(Student s) {
this.students[numStudents++] = s;
}
public static void main(String[] args) {
// create our aggregator object
InitializerDemo id = new InitializerDemo();
// set the instructor
id.setInstructor(new Instructor("Sally"));
// add the students
id.addStudent(new Student("Sam"));
id.addStudent(new Student("Rajiv"));
id.addStudent(new Student("Jennifer"));
id.addStudent(new Student("Test Student"));
// output
System.out.println(id);
}
public String toString() {
String s = "Instructor = " + instructor + "\n" +
"Number of students = " + numStudents + "\n" +
"Students: " + Arrays.toString(students) + "\n";
return s;
}
}
class Student {
private String name;
// instance initializer block
{
name = "noname";
}
public Student() {
}
public Student(String name) {
this.name = name;
}
public String toString() { return name; }
}
class Instructor {
private String name;
// instance initializer block
{
name = "noname";
}
public Instructor() {
}
public Instructor(String name) {
this.name = name;
}
public String toString() { return name; }
}
I need help with that addStudent Method
These are the instructions and sorry to confuse all you guys and thank you for putting time to help me
change the instance variables representing the number of students and the Student array in the aggregator object to private static variables.
• change the addStudent method in the aggregator object from an instance method to a static method
• Remove all initialization/instantiation operations from the aggregator object’s default constructor; the constructor can simple be an empty method { }
• provide a static initializer block in the aggregator object which does the following:
o initializes the number of students to 0
o instantiates the student array
o adds a single student named “Test Student” to the array using the addStudent method
Change
this.students[numStudents++] = s;
to
students[numStudents++] = s;.
I believe that should work.
You also have to initialize the students, so change
private static Student[] students;
to
private static Student[] students = new Student[MAX_STUDENTS];
I want to order nodes' chosen string variables. this is an homework due to tomorrow.
public void sortSongName() {
DefaultSongs sortedList = new DefaultSongs();
int temp= Integer.MAX_VALUE;
Song curr=root;
Song hold = null;
while(root.nextSong != null) {
if(curr.getSongName().charAt(0)<hold.getSongName().charAt(0)) {
hold=curr;
curr=root.nextSong;
}else {
curr=root.nextSong;
}
sortedList.createSong(root.nextSong.getSongName(),root.nextSong.getBandName() , root.nextSong.getDuration());
deleteSong(root.nextSong.getSongName());
sortSongName();
}
}
Assuming your song class look something like this
public class Song {
private String name;
public String name() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
And the DefaultSongs class is just a repo with a list of Songs
public class DefaultSongs {
private final List<Song> songList;
public DefaultSongs() {
this.songList = new ArrayList<>();
}
public List<Song> songList() {
return songList;
}
}
Simplest way would be to use java stream
public void sortSongsByName(){
songList.stream().sorted(Comparator.comparing(Song::name));
}
The simplest way is to use Collections.sort();
For example:
List<String> songs = Arrays.asList("Bam","Cam", "Am","Dam");
Collections.sort(songs);
System.out.println(songs);
This will give you the list in alphabetical order.
I am trying to return the array of students in a tester class for the Course class but I keep getting a .class expected error. I've tried to do
students[].TestCourse but that doesn't work either.
public class Course {
private String courseName;
private String[] students = new String[4];
private int numberOfStudents;
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
if (numberOfStudents == students.length) {
String [] copy = new String [students.length*2];
System.arraycopy(students,0,copy,0,students.length);
students = copy;
}
students[numberOfStudents] = student;
numberOfStudents++;
}
public String[] getStudents() {
return students;
}
public void dropStudent(String student) {
for (int i=0;i<students.length;i++) {
if (students[i]==student) {
students[i] = null;
}
for (i=i;i<students.length-1;i++) {
students[i] = students[i+1];
}
}
}
}
public class TestCourse {
public static void main() {
Course compScience = new Course("Computer Science");
compScience.addStudent("Jack");
compScience.addStudent("Dean");
compScience.addStudent("Leon");
compScience.dropStudent("Dean");
System.out.println("The students currently in this course are "+ students[]);
}
}
Change the line in your main method to:
System.out.println("The students currently in this course are "+ Arrays.toString(compScience.getStudents()));
and it should fire up!
All you've done is try to call the field of a class directly when you need to access it via the reference you created Course compScience = new Course("Computer Science"); ... then call it's method getStudents() as follows compScience.getStudents(). To get the contents of the array you then need to wrap this method call in Arrays.toString() as above.
I'm learning Java and trying out stuff. I want to be able to print students' names with their courses and grades. I have written the following classes to achieve that but since I'm a newbie, I'm wondering if I have done it correctly. The code does display what I want but how can I best optimize it?
Subject class:
public class Subject {
private String subjName;
private int subjGrade;
public Subject(String subjName, int subjGrade) {
this.subjName = subjName;
this.subjGrade = subjGrade;
}
public void setName(String name) {
this.subjName = name;
}
public String getName() {
return subjName;
}
public int getGrade(){
return subjGrade;
}
#Override
public String toString() {
return String.format( getName() + ", Grade:" + getGrade());
}
}
StudentSubJGrade class:
import javax.swing.text.html.HTMLDocument;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class StudentSubJGrade {
String name;
Subject[] subjects;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setSubjects(Subject[] subjects) {
this.subjects = subjects;
}
public StudentSubJGrade(String name, Subject[] subjects) {
this.name = name;
this.subjects = subjects;
}
#Override
public String toString() {
return String.format("Name:" + getName() + " Subjects:" + Arrays.toString(subjects));
}
}
I feel I can add the subjects via the ArrayList but couldn't come up with how to do it after hours of trials. How can this be done without using arrays as I have done?
Driver class:
import java.util.ArrayList;
public class StudentSubjGradeDriver {
public static void main(String[] args) {
ArrayList<StudentSubJGrade> test = new ArrayList<>();
ArrayList<StudentSubJGrade> test2 = new ArrayList<>();
Subject[] subjects = new Subject[3];
subjects[0] = new Subject("Maths",80);
subjects[1] = new Subject("Physic",90);
subjects[2] = new Subject("Chemistry",70);
Subject[] subjects1 = new Subject[4];
subjects1[0] = new Subject("Maths",80);
subjects1[1] = new Subject("Physic",90);
subjects1[2] = new Subject("Chemistry",70);
subjects1[3] = new Subject("Geography",90);
test.add(new StudentSubJGrade("Anita",subjects));
test2.add(new StudentSubJGrade("James",subjects1));
System.out.println(test);
System.out.println(test2);
}
}
After carrying out suggestions, I tried improving on the code by creating the subjects as ArrayLists but I'm having trouble with it:
ArrayList<Subject> subjects;
public StudentSubJGrade(String name, ArrayList<Subject> subjects) {
this.name = name;
this.subjects = subjects;
}
Now in the main method, I tried the following but I'm getting an error:
ArrayList<StudentSubJGrade> test = new ArrayList<>();
ArrayList<Subject> st = new ArrayList<>();
st.add(new Subject("Maths",90));
test.add("Anita",st);
The problems with your code are that a) you are passing an array to the constructor without copying it, and b) you cannot change the subjects later.
For example, for a) say that you do the following:
Subject[] subjects = new Subject[] {
new Subject("Maths",80),
new Subject("Physic",90),
new Subject("Chemistry",70),
new Subject("Geography",90)
};
StudentSubJGrade student = new StudentSubJGrade("Hassan", subjects );
So far, so good. But now:
subjects[ 0 ] = null;
And suddenly your StudentSubJGrade student object has a null in its subjects.
This effect has to do with arrays being objects (like Student), instead of value types (as in int x = 5), which implies that in your case both references will point to the same array.
Take look here for a demo on shared array objects.
You can avoid this by changing the method setSubjects().
public void setSubjects(Subject[] subjects)
{
this.copySubjects( subjects );
}
private void copySubjects(Subject[] subjects)
{
final int arraySize = subjects.length;
this.subjects = new Subject[ arraySize ];
System.arraycopy( subjects, 0, this.subjects, 0, arraySize );
}
public StudentSubJGrade(String name, Subject[] subjects) {
this.name = name;
this.copySubjects( subjects );
}
If you need to change the subjects later, then you need to change the array inside the class for an ArrayList, and never expose it. You can get the subjects with the toArray() method, and accept an array or an enumeration to load it.
public void clearSubjects()
{
this.subjects.clear();
}
public void addSubjects(Subject[] subjects)
{
this.appendSubjects( subjects );
}
private void appendSubjects(Subject[] subjects)
{
this.subjects.addAll( subjects );
}
public Subject[] getSubjects()
{
return this.subjects.toArray( new Subject[ 0 ] );
}
public StudentSubJGrade(String name, Subject[] subjects)
{
this.name = name;
this.appendSubjects( subjects );
}
private ArrayList<Subject> subjects;
Hope this helps.
You have to use arrays because the StudentSubJGrade constructor expects the second argument to be a Subject[]. However, you can simplify your creation of the arrays:
import java.util.ArrayList;
public class StudentSubjGradeDriver {
public static void main(String[] args) {
ArrayList<StudentSubJGrade> test = new ArrayList<>();
ArrayList<StudentSubJGrade> test2 = new ArrayList<>();
Subject[] subjects = new Subject[] {
new Subject("Maths",80),
new Subject("Physic",90),
new Subject("Chemistry",70)
};
Subject[] subjects1 = new Subject[] {
new Subject("Maths",80),
new Subject("Physic",90),
new Subject("Chemistry",70),
new Subject("Geography",90)
};
test.add(new StudentSubJGrade("Hassan",subjects));
test2.add(new StudentSubJGrade("James",subjects1));
System.out.println(test);
System.out.println(test2);
}
}
I wrote the two departments and when I try to read to the class from the chief and I have a problem compiling and I can not understand what the problem is, I'd love to help.
in main the error is on the line : 5.
Main:
public class main {
public static void main(String[]args){
Lecturer LecturerObject = new Lecturer("Dani",3,"Banana",1001);
The error is here >>Lecturer[] L1 = new Lecturer("Dani",2,"Banana",1001);
College FirstCollege = new College("Hmpson",2, L1);
}
}
First Class:
public class Lecturer {
public String nameOfLecturer = "";
public int numOfTimesPenFalls = 0;
public String favoriteIceCream = "";
public int numAuto = 1000;
//constructors, same name like class
public Lecturer(String name, int TimesPenFalls, String IceCream,
int num) {
nameOfLecturer = name;
numOfTimesPenFalls = TimesPenFalls;
favoriteIceCream = IceCream;
numAuto = num;
int maxLecturer=10;
}
//Copy constructor
public Lecturer(Lecturer other){
nameOfLecturer = other.nameOfLecturer;
numOfTimesPenFalls = other.numOfTimesPenFalls;
favoriteIceCream = other.favoriteIceCream;
numAuto = other.numAuto;
}
}
Secoand Class:
public class College {
public String CollegeName = "";
public int numOfLecturers = 0;
public Lecturer[] allLecturers;
// constructors, same name like class
public College(String name, int numLecturers, Lecturer[] dataBase) {
CollegeName = name;
numOfLecturers = numLecturers;
allLecturers = dataBase;
int maxLecturer = 10;
}
// getter, only private
public String getCollegeName() {
return CollegeName;
}
// setter, only private
public void setCollegeName(String newcollegeName) {
CollegeName = newcollegeName;
}
public boolean newLecturer(Lecturer addNewLecturer, int maxLecturer) {
if (numOfLecturers < maxLecturer || numOfLecturers == maxLecturer) {
numOfLecturers += 1;
return true;
} else {
System.out.print("Sorry, Max Lecturer!");
return false;
}
}
public void sortLecturer(Lecturer[] arrAllLecturers) {
int numOfTimesPenFalls = 0;
}
}
I'm first started with java I would be happy for a detailed explanation where is the problem, thank you very much.
This statement here
Lecturer[] L1 = new Lecturer("Dani",2,"Banana",1001); is wrong because you have defined L1 as an array but you are initializing it as a simple Object....
in some IDEs like eclipse, the compiler will complain with a message like
Type mismatch: cannot convert from Lecturer to Lecturer[]
Ergo: you need to init L1 as it is, as an array:
do this:
Lecturer[] L1 = new Lecturer[]{new Lecturer("Dani",2,"Banana",1001)};
now you have an array with one Lecturer object inside..
You are trying to assign array Lecture object to array, which can be done in following manner correctly.
Lecturer[] L1 = new Lecturer[] {new Lecturer("Dani",2,"Banana",1001)};