Before you read ahead, this is for my homework so the questions/answers are going to be specific.
I am writing some code that takes a student's name and adds it to the student ArrayList. I have a class for students and another class for a course (the course is where the add student and the ArrayList is ). The problem that I am having is that the code is restricting me from using some methods of the student class even though I have used them before. Also, the newly created student has to return the reference of the student, and if it fails it will return null. I have tried that but it has given me errors and I am unsure on how to incorporate the if-else function within the method.
Below is my code for the student class:
public class Student {
// instance fields
//class implementation
private String name;
private String surname;
private long studentId;
private String loginId;
private static int count = 10000001;
private double[] quizMarks; //declare as an array
//constuctors
public Student(String name, String surname) {
this.name = name;
this.surname = surname;
this.studentId = studentId;
quizMarks = new double[0];//initialize array
}
//accessors and mutator methods
//set student's name and surname. Changing student's name does not affect the students' loginID
public void Name(String name, String surname) {
}
//returns name and surname separated by comma (name, surname)
public String setName() {
return name + ", " + surname;
}
}
class for Course:
import java.util.ArrayList;
public class Course{
private ArrayList<Student> students;
ArrayList<Double> quiz;
public Course() {
students = new ArrayList<Student>();
quiz = new ArrayList<Double>();
}
Student addStudent (String name, String familyName){
students.add(setName(Name(name, familyName)));
return null;
}
Student deleteStudent(long studentId){
students.remove(studentId);
return null;
}
}
}
This,
students.add(setName(Name(name, familyName)));
is not correct. You don't want to add a String to stduents you want a Student. Like,
students.add(new Student(name, familyName));
import java.util.ArrayList;
public class Course{
// variables and constructors
Student addStudent (String name, String familyName){
students.setName(name, familyName);
return null;
}
Student deleteStudent(long studentId){
students.remove(studentId);
return null;
}
}
}
There exists no Add or remove method in class Student so either you can add them in your format or correct that format.
public class Student {
// variables
// constuctors
public Student(String name, String surname) {
this.name = name;
this.surname = surname;
this.studentId = studentId;
quizMarks = new double[0];//initialize array
}
public Student remove(Student obj) {
obj = null; //Destroying the reference
}
public void Name(String name, String surname) {
}
//returns name and surname separated by comma (name, surname)
public String setName() {
return name + ", " + surname;
}
}
Related
These are my requirements:
Write a program (Person) that has the following attributes: name, adress, age.
Write four constructors
Write get set methods
Write a toString method.
Write a seperate program (TestClass) and let the user enter the name, adress and age in three different dialogboxes and then create an object of the class Person and store the data in this object.
In the same way, let the user create four more objects but use one of the constructors with each object.
View the data for each object through a dialog box, using the toString method.
That was my instructions and below is my code for the program(class) Person:
public class Person
{
private String name;
private String adress;
public int age;
public Person(String name, String adress, int age)
{
this.name=name;
this.adress=adress;
this.age=age;
}
public Person(String name, int age)
{
this.name=name;
this.age=age;
this.adress="";
}
public Person(String name, String adress)
{
this.name=name;
this.adress=adress;
this.age=0;
}
public Person(String name)
{
this.name=name;
this.adress="";
this.age=0;
}
public Person()
{
this.name="";
this.adress="";
this.age=0;
}
public void setName(String name)
{
this.name=name;
}
public void setAdress(String adress)
{
this.adress=adress;
}
public void setAge(int age)
{
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String getAdress()
{
return adress;
}
public String toString()
{
return " Name : " + name + " Age: " + age+ " " + " Adress: " + adress;
}
}
And hereeee is the code for my program TestClass. Look at the comments
import javax.swing.JOptionPane;
public class TestClass
{
public static void main(String[]args)
{
// 5. Write a seperate program (TestClass) and let the user enter the name, adress and age
int r1;
String name=JOptionPane.showInputDialog("Whats your name ?");
String adress=JOptionPane.showInputDialog("Whats your adress? ");
String sR1=JOptionPane.showInputDialog("What's your age? ");
r1=Integer.parseInt(sR1);
Person p1=new Forening(name, adress, r1);
JOptionPane.showMessageDialog(null,p1.toString());
// 6.let the user create four more objects but use one of the constructors with each object.
Person p3=new Person("Johanna", 2004);
JOptionPane.showMessageDialog(null,p3.toString());
Forening p4=new Person("John", "JavaScriptstreet 1");
JOptionPane.showMessageDialog(null,p4.toString());
Person p5=new Person("Sandra");
JOptionPane.showMessageDialog(null,p5.toString());
Obviously I'm not doing soooomething right!! It's the part where I'm supposed to let the user input data through dialog boxes and let the user create objects of the class to store the data and then show the data that I'm struggling with..
Im trying to create a student arraylist to a a course class so that when a student is added the arraylist is increases. this is the code I have so far:
import java.util.ArrayList;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Saj
*/
public class Course {
private String courseName;
private int noOfStudents;
private String teacher;
public static int instances = 0;
//Getters
public String getCourseName(){
return this.courseName;
}
public int getNoOfStudents(){
return this.noOfStudents;
}
public String getTeacher(){
return this.teacher;
}
//Setters
public void setCourseName(String courseName){
this.courseName = courseName;
}
public void setNoOfStudents(int noOfStudents){
this.noOfStudents = noOfStudents;
}
public void setTeacher(String teacher){
this.teacher = teacher;
}
/**
* Default constructor. Populates course name, number of students with defaults
*/
public Course(){
instances++;
this.noOfStudents = 0;
this.courseName = "Not Set";
this.teacher = "Not Set";
}
/**
* Constructor with parameters
* #param noOfStudents integer
* #param courseName String with the Course name
* #param teacher String with the teacher
*/
public Course(int noOfStudents, String courseName, String teacher){
this.noOfStudents = noOfStudents;
this.courseName = courseName;
this.teacher = teacher;
}
}
Im unsure how to implement the array list. Can someone point me in the right direction.
With a little bit of research you can find many tutorials to achieve what you intend, but i'll try to set you in the right path just so you have an answear and somewhere to start.
What is a Student ?
Is it a String containing just a name, is it an object that represents a student that can have some properties ?
One example is
public class Student{
private int number;
private String name;
private int age;
// Basically anything that makes sense for a student.
public Student(int number, String name, int age){
this.number = number;
this.name = name;
this.age = age;
}
// .... Getters and Setters.
}
You need some place to store every Student added to the course, that is what the ArrayList is for i.e
List<Student> students = new ArrayList<Student>();
Student foo = new Student(23, "Foo", 22);
students.add(foo); // This is how you add to a List (in this case a List of Student objects and more precisely an ArrayList of Students).
You will need to keep the list in your course class as an instance variable, and add a method in wich you can pass a student and inside the method all you have to is add to your list of students, you may even do some validation if you want.
If you have more doubts first search for a solution before asking questions that can easily be found.
Here are some references:
Java List
Java ArrayList
EDIT the way you are adding your students is almost done but you have an error and also your list of students only resides inside the constructor, wich means you cannot use the list for saving students outside.
Below is the correct code
/**
* Constructor with parameters
* #param noOfStudents integer
* #param courseName String with the Course name
* #param teacher String with the teacher
*/
public Course(int noOfStudents, String courseName, String teacher){
this.studentList = new ArrayList<Student>(); // The declaration is in above in your class, as an instance variable.
this.courseName = courseName;
this.teacher = teacher;
}
ArrayList<Student> studentList; // You can move this so it sits above besides your other variables, but it will also work like this.
public boolean addStudent(Student student){
if (student==null || studentList.contains(student)) { // You had Student.contains, wich will give an error because Student (class) doesnt have a static method named contains.
return false;
}
studentList.add(student); // you had the same problem here, you had Student.add(student), wich is wrong and it would not compile.
return true;
}
Be sure that you have created the Student class and it is without any errors.
Tested and working code, change it to fullfill your needs more precisely
import java.util.ArrayList;
public class Course {
private String courseName;
private int noOfStudents;
private String teacher;
public static int instances = 0;
private ArrayList<Student> studentList;
//Getters
public String getCourseName(){
return this.courseName;
}
public int getNoOfStudents(){
return this.noOfStudents;
}
public String getTeacher(){
return this.teacher;
}
//Setters
public void setCourseName(String courseName){
this.courseName = courseName;
}
public void setNoOfStudents(int noOfStudents){
this.noOfStudents = noOfStudents;
}
public void setTeacher(String teacher){
this.teacher = teacher;
}
/**
* Default constructor. Populates course name, number of students with defaults
*/
public Course(){
instances++;
this.noOfStudents = 0;
this.courseName = "Not Set";
this.teacher = "Not Set";
}
/**
* Constructor with parameters
* #param noOfStudents integer
* #param courseName String with the Course name
* #param teacher String with the teacher
*/
public Course(int noOfStudents, String courseName, String teacher){
this.studentList = new ArrayList<Student>();
this.courseName = courseName;
this.teacher = teacher;
}
public boolean addStudent(Student student){
if (student==null || studentList.contains(student)) {
return false;
}
studentList.add(student);
return true;
}
public void printStudents(){
for(Student s : studentList)
System.out.println(s.getName() + ", with " + s.getAge() + " year(s)");
}
public static class Student{
private int number;
private String name;
private int age;
// Basically anything that makes sense for a student.
public Student(int number, String name, int age){
this.number = number;
this.name = name;
this.age = age;
}
// .... Getters and Setters.
public int getNumber(){
return this.number;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
}
// Testing code
public static void main(String[] args){
Course oop = new Course(6, "Object Oriented Programming", "LeBron James");
oop.addStudent(new Course.Student(6, "Michael Jordan", 56));
oop.addStudent(new Course.Student(23, "Kyrie Irving", 24));
oop.addStudent(new Course.Student(14, "Kevin Love", 27));
System.out.println(oop.getCourseName() + " has the following students");
oop.printStudents();
}
}
Just add attribute to your class
List<Student> students;
In constructors, initialize this list:
students = new ArrayList<>();
Create method to add student to list:
public boolean addStudent(Student stud) {
if (stud == null || students.contains(stud)) {
return false;
}
students.add(stud);
return true;
}
Also check https://docs.oracle.com/javase/8/docs/api/java/util/List.html for documentation of list.
Question is, do you want to add students in constructor? If so, add parameter to your constructor
public Course(int noOfStudents, String courseName,
String teacher, List<Student> students){
this.noOfStudents = noOfStudents;
this.courseName = courseName;
this.teacher = teacher;
this.students = new Arraylist<>(students);
}
I am trying to solve an assignment in my Java class. I am stuck and need a little help.
I am trying to create a method in my Group class that will display the group name and the 4 students in the group. My code currently displays the group name and the memory location of my student inside my array.
public class Group {
/**-------Declaring attributes----*/
String groupName;
int newStudentCount;
/**----------------------------*/
/**--------Constructor------------*/
public Group(String givenGroupName) {
groupName = givenGroupName;
}
Student[] students = new Student[4];
/**----------------------------*/
/**--------Method------------*/
void addStudent(Student st) {
students[newStudentCount] = st;
++newStudentCount;
System.out.println("New student: " +st.getName());
}
public String getGroup() {
return "Group = " + groupName;
}
public Student getStudent(){
return students[0];
}
}
In my App class I have this:
public class App {
public static void main(String[] args) {
Group g1 = new Group("Pink Pony Princesses");
Student st1 = new Student("Joshua Mathews");
st1.getName();
g1.addStudent(st1);
Student st2 = new Student("Jame Brooks");
g1.addStudent(st2);
Student st3 = new Student("Mike Myers");
g1.addStudent(st3);
Student st4 = new Student("Christie Richie");
g1.addStudent(st4);
System.out.println(g1.getGroup()+ " " + g1.getStudent());
}
This is my Student class:
public class Student {
/**-------Declaring attributes----*/
String name;
String degree;
int age;
/**----------------------------*/
/**--------Constructor------------*/
Student(String givenName){
name = givenName;
}
Student(String givenName, String givenDegree, int givenAge) {
name = givenName;
degree = givenDegree;
age = givenAge;
}
/**--------- METHODS --------*/
//Array
public final String [] activities = {
"Working on Homework", "Playing a Game", "Taking a Nap"
};
String getInfo(){
return name + age + degree;
}
String getName() {
return name;
}
int getAge(){
return age;
}
String getDegree() {
return degree;
}
String whatsUp(){
Random rand = new Random();
int randomIndex = rand.nextInt(activities.length);
String returnActivity = activities[randomIndex];
return returnActivity;
}
I'm not sure how to call my array to display the 4 names, and not the memory location of them. Any help would be greatly appreciated.
I can deduce a couple of things from your question.
First, you are returning only the student at index 0 of the Student array held within your Group object. If you want to return all students your method signature should have a Student[] as the return type rather than a Student object.
If you follow the above prompt then you will have to iterate through the returned array printing each Student object.
Regardless of which implementation you choose the reason you print out a memory reference rather than a String object is that you have not overridden toString within your Student class.
Something like this will print out Student data when passed to a System.out call:
#Override
public String toString() {
return someStudentData;
}
You can go with what andrewdleach said by implementing toString(). OR
To print all student names your method should be something like:
public String getStudent(){
String studentNames = "";
for(Student stu: students){
studentNames+= stu.getName() + ",";
}
return studentNames;
}
I have a simple java program I and I cannot figure out why the setter for a class will not set the correct value.
I have a class Employee, a class Department, a class Company. Once I am able to set correct values to the fields of an Employee instance I will then store that employee in a arraylist of employees in an instance of Department(arrayList field).
The class called Employee. It has four fields, String fName, String lName, int age, String department. I am able to set fName and lName though age is always set to 0 and department is always set to null.
Here is the code for the employee class:
public class Employee {
private String fName;
private String lName;
private String department;
private int age;
//getters and setters for the private fields of the Employee class
public void setAge(int num){
num = age;
}
public int getAge(){
return age;
}
public void setDepartment(String dep){
dep = department;
}
public String getDepartment(){
return department;
}
public void setfName(String afName){
fName = afName;
}
public String getfName(){
return fName;
}
public void setlName(String alName){
lName = alName;
}
public String getlName(){
return lName;
}
}
Here is the code for a method called addEmployee:
public void AddEmployee(Department depInstance){
String firstName = JOptionPane.showInputDialog("Enter employee First name");
String lastName = JOptionPane.showInputDialog("Enter employee last name");
int empAge = Integer.parseInt(JOptionPane.showInputDialog("Enter employee age"));
String empDep = JOptionPane.showInputDialog("Enter employee department");
Employee employeeToAdd = new Employee();
employeeToAdd.setfName(firstName);
employeeToAdd.setlName(lastName);
employeeToAdd.setAge(empAge);
employeeToAdd.setDepartment(empDep);
//test input and variable setting
System.out.println("--------Inputs------");
varTester(firstName,lastName,empAge,empDep);
System.out.println("--------Recorded Vals------");
varTester(employeeToAdd.getfName(), employeeToAdd.getlName(),employeeToAdd.getAge(),employeeToAdd.getDepartment());
public static void varTester(String empfName, String emplName, int empAge, String empDep){
System.out.println(empfName);
System.out.println(emplName);
System.out.println(empAge);
System.out.println(empDep);
}
}
This is the output from the test method varTester():
--------Inputs------
Somefirstname
Somelastname
32
Accounting
--------Recorded Vals------
Somefirstname
Somelastname
0
null
I test the values received from the showInputDialog's and it is the correct values I want to store int the class instance fields of employeeToAdd though only the first and last name values are set and not the age or department. Can someone point me in the right direction. Thank you.
You got the setter backwards. It should be :
public void setAge(int num){
age = num;
}
You have the same error in setDepartment.
You are supposed to assign to the member variable, not to the argument of the setter method.
Your setter sets the argument not the private field.
public void setAge(int num){
num = age;
}
public void setDepartment(String dep){
dep = department;
}
Change it to:
public void setAge(int num){
age = num;
}
public void setDepartment(String dep){
department = dep;
}
It should be:
public void setAge(int num){
age = num;
}
public void setDepartment(String dep){
department = dep;
}
I have a homework assignment problem that looks like this:
(20 pts) Create a Student class with the following:
A private String variable named “name” to store the student’s name
A private integer variable named “UFID” that contains the unique ID number for this student
A private String variable named “DOB” to store the student’s date of birth
A private integer class variable named numberOfStudents that keeps track of the number of students that have been created so far
A public constructor Student(String name, int UFID, String dob)
Several public get/set methods for all the properties
getName/setName
getUFID/setUFID
getDob/setDob
Write a test program, roster.java, that keeps a list of current enrolled students. It should have methods to be able to enroll a new
student and drop an existing student.
I'm not asking anyone to do this assignment for me, I just really need some general guidance. I think I have the Student class pretty well made, but I can't tell exactly what the addStudent() and dropStudent() methods should do - should it add an element to an array or something or just increments the number of students? The code I have so far looks like this.
public class Student {
private String name;
private int UFID;
private String DOB;
private static int numberOfStudents;
public Student(String name, int UFID, String DOB) {
this.name = name;
this.UFID = UFID;
this.DOB = DOB;
}
public String getDOB() {
return DOB;
}
public void setDOB(String dOB) {
DOB = dOB;
}
public int getUFID() {
return UFID; }
public void setUFID(int uFID) {
UFID = uFID; }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public void setNumberOfStudents(int numberOfStudents) {
Student.numberOfStudents = numberOfStudents;
}
public static void addStudent(String name, int UFID, String DOB) {
numberOfStudents++;
}
public static void dropStudent(String name) {
numberOfStudents--;
}
}
Any guidance as I finish this up would be greatly appreciated.
The assignment writes itself: you need a Roster class that owns and maintains a collection of Students:
public class Roster {
private Set<Student> roster = new HashSet<Student>();
public void addStudent(Student s) { this.roster.add(s); }
public void removeStudent(Student s) { this.roster.remove(s); }
}