how can i remove a student from the course
i tried enrolledStudents.remove("");
since the user will have to put the name of the student that previously enrolled to drop him.
public class Course {
public String courseName;
public int maxNumberofStudentsAllowedtoEnroll=100;
private ArrayList<String> enrolledStudents = new ArrayList<String>(100);
public Course(String courseName){
this.courseName = courseName;
}
public void addStudent(String student){
if(enrolledStudents.size() == maxNumberofStudentsAllowedtoEnroll){
System.out.println("You have reached the maximum numbers of students allowed in a course! \n"
+ "Max allowed: "+maxNumberofStudentsAllowedtoEnroll);
return;
}
enrolledStudents.add(student);
}
public int getNumberStudents(){
return enrolledStudents.size();
}
public void showStudents(){
for(int i=0; i<enrolledStudents.size(); i++){
System.out.println(enrolledStudents.get(i));
}
}
public void dropStudent(String student){
enrolledStudents.remove(" ");
}
ive searched up on the net about it. But all the elements of an array are already assigned.
im sorry if im not clear, basically what i want to do is:
if i add a student when i press 1, and then type: "john"
and then do the same with: "albert"
how do i do so that when i press 2 and enter the name of the student to drop, in this case: "john"
So that when I press 3 to view the students only "albert" shows up.
Try to remove the quotation marks "" from the .remove method and use the String parameter student inside the remove method. Below you may find the answer. Hope this helps.
public class Course {
public String courseName;
public int maxNumberofStudentsAllowedtoEnroll=100;
private ArrayList<String> enrolledStudents = new ArrayList<String>(100);
public Course(String courseName){
this.courseName = courseName;
}
public void addStudent(String student){
if(enrolledStudents.size() == maxNumberofStudentsAllowedtoEnroll){
System.out.println("You have reached the maximum numbers of students allowed in a course! \n"
+ "Max allowed: "+maxNumberofStudentsAllowedtoEnroll);
return;
}
enrolledStudents.add(student);
}
public int getNumberStudents(){
return enrolledStudents.size();
}
public void showStudents(){
for(int i=0; i<enrolledStudents.size(); i++){
System.out.println(enrolledStudents.get(i));
}
}
public void dropStudent(String student){
enrolledStudents.remove(student);
}
Instead of "" just write student.
public void dropStudent(String student){
enrolledStudents.remove(student);
}
that's it. You can check it by calling System.out.println(course.enrolledStudents); before and after dropStudent function.
Related
I have three classes in my program. Ship.java, Cabin.java and Passenger.java. According to the program a single cabin can hold upto a maximum of 3 passengers. I'm trying to set passenger details but i keep getting this error
Cannot invoke "classes.Passenger.setFirstName(String)" because
"classes.Main.myShip[0].passenger[0]" is null at
classes.Main.main(Main.java:22)
Ship.java
public class Ship
{
public static Scanner scanner = new Scanner(System.in);
public static Cabin[] myShip = new Cabin[12];
public static void main(String[] args)
{
for (int count = 0; count < 12; count++)
{
myShip[count] = new Cabin();
}
myShip[0].passenger[0].setFirstName("a");
}
}
Cabin.java
public class Cabin
{
int cabinNumber;
Passenger[] passenger = new Passenger[3];
public Cabin()
{
}
public Cabin(int cabinNumber, Passenger[] passenger)
{
this.cabinNumber = cabinNumber;
this.passenger = passenger;
}
public void setCabinNumber(int cNumber)
{
cabinNumber = cNumber;
}
public int getCabinNumber()
{
return cabinNumber;
}
}
Passenger.java
public class Passenger
{
String firstName;
String lastName;
int expenses;
public Passenger()
{
}
//Constructors
public Passenger(String cabinFirstName, String cabinLastName, int pExpenses)
{
firstName = cabinFirstName;
lastName = cabinLastName;
expenses = pExpenses;
}
public void setFirstName(String cabinFirstName)
{
firstName = cabinFirstName;
}
public String getFirstName()
{
return firstName;
}
public void setLastName(String cabinLastName)
{
lastName = cabinLastName;
}
public String getLastName()
{
return lastName;
}
public void setExpenses(int pExpenses)
{
expenses = pExpenses;
}
public int getExpenses()
{
return expenses;
}
}
Please be kind enough to help me out.
Your model is wrong. A ship can (and does) have cabins with no occupants. You have provided no way to have unoccupied cabins. Your cabins need to be fully booked before the ship can be built!
I would consider redefining your Cabin class to be constructed empty -- which means it would have a constructor with a signature like Cabin(), and then provide a way to assign Passengers to Cabins. Maybe this would be a method in the Cabin class, like
boolean assignPassenger(Passenger p) {
... check occupancy...
... return false if full up ...
... otherwise add 'p' to the passenger array ...
... and return true ...
}
You're halfway there in that you're attempting to set the Cabins in the Ship by using a Cabin() constructor -- which is essentially an empty Cabin -- but you have not actually implemented a constructor with that signature.
What I'm getting at here is that, rather than just tweaking some Java, I think you should rethink it a bit. You'd want, I think, to be able to have unoccupied cabins and to be able to determine which cabins are occupied.
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.
public class studentDriver {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many students are there?: ");
int numberOfstuds = scan.nextInt();
int[] nOEarray = new int[numberOfstuds];
System.out.println("\nEnter names of students up to the entered amount (" + numberOfstuds + "):");
String[] namesArray = new String[numberOfstuds];
for (int i = 0; i < numberOfstuds; i++) {
namesArray[i] = scan.next();
}
System.out.println(Arrays.toString(namesArray));
}
}
That is part of my code for letting user input array size, however I am tasked with using the header below just for a method to get the size of the array, but I have tried inserting it and keep getting different error messages such as needs body(if I put semi-colon) or "requires ';'" if I don't and when I put curly braces around the section where it gets the array size it returns errors :Syntax error, insert "[ ]" to complete Dimension
- Syntax error, insert ";" to complete BlockStatements
- Syntax error on token "create", AnnotationName expected after
this token
public static Student[] create()
Here is the Student class
public class Student {
//private data members
private String name;
private long idNUmber;
//constructor
public Student(){
name="Unassigned";
idNUmber=0;
}
//overloaded constructor
public Student(String x, long y) {
name=x;
idNUmber=y;
}
//getters
public String getName() {
return name;
}
public long getIdNUmber() {
return idNUmber;
}
//setters
public void setName(String n) {
name=n;
}
public void setIdNUmber(long i) {
idNUmber=i;
}
//override
public String toString() {
return "Name: "+getName()+"\nID number: "+getIdNUmber();
}
I try to write a code which will have a basic menu with some options. These options are the following methods: AddStudent, changeName, setGrade and so on. I have created an object called Student which has a name, a grade and an age. I want to add Students in an linked list but when I use the method add it does not work. Here is my code:
import java.util.*;
class Student {
int age;
int grade;
String name;
static LinkedList ll = new LinkedList();
public Student (String n) { //we create here a student with a name and an age
name=n;
age=0;
grade=0;
}
//-------------------------------------------------------------------------
public void p(String x) {
System.out.println(x);
}
public void addStudent() {
Scanner s = new Scanner(System.in);
p("Enter the name that you want");
String f = s.nextLine();
Student a = new Student(f);
ll.add(a);
}
public void changeName() { //this method is to change the name of a student
Scanner s = new Scanner(System.in);
p("Enter whose name you want to change");
String c = s.nextLine();
p("Enter the name that you want");
String b = s.nextLine();
}
public void setGrade(Student a) { //this method is to put the student's grade
Scanner s = new Scanner(System.in);
p("Enter the grade that you want");
int g = s.nextInt();
a.grade=g;
}
public void setAge(Student a) { //This method is to put the student's grade
Scanner s = new Scanner(System.in);
p("Enter the age that you want");
int h = s.nextInt();
a.age=h;
}
public String getName(Student a) {
return a.name;
}
public int getAge(Student a) {
return a.age;
}
public int getGrade(Student a) {
return a.grade;
}
}
The problem is at the method of addStudent. Is there any other ways,as well, with which I can make the same project?
Think about this logically. You have a Student class that represents a single Student. Why would a Student have a List of Student's? That makes no sense.
Wouldn't you have a program like Course or something that would hold the list of Students? That is where your List belongs. And don't use static unless you have a compelling reason (rare).
Here is a start for the Course class, that uses the Student to store student information and stores it in your LinkedList within the Course. You still need to implement the findStudent method and probably a method to print the List:
Class Course:
import java.util.LinkedList;
import java.util.Scanner;
public class Course {
LinkedList ll = new LinkedList();
Scanner s = new Scanner(System.in);
public void addStudent() {
p("Enter the name that you want");
String f = s.nextLine();
Student a = new Student(f);
ll.add(a);
}
public void changeName() { //this method is to change the name of a student
Student student = findStudent();
p("Enter the name that you want");
String newName = s.nextLine();
//student.setName(newName);
}
public void setGrade() { //this method is to put the student's grade
Student student = findStudent();
p("Enter the grade that you want");
int grade = s.nextInt();
//student.setGrade(grade);
}
public void setAge() { //This method is to put the student's grade
Student student = findStudent();
p("Enter the age that you want");
int age = s.nextInt();
student.setAge(age);
}
public Student findStudent(){
p("Which student did you want to change? Please enter their name:");
String name = s.nextLine();
//Find student in the list - left for the author
Student student = null;
return student;
}
//-------------------------------------------------------------------------
public void p(String x) {
System.out.println(x);
}
public static void main(String[] args) {
Course course = new Course();
course.addStudent();
course.addStudent();
course.changeName();
course.setGrade();
}
}
And the modified Student class:
import java.util.*;
public class Student {
int age;
int grade;
String name;
public Student (String n) { //we create here a student with a name and an age
name=n;
age=0;
grade=0;
}
public void setName(String name) {
this.name = name;
}
public void setGrade(int grade) {
this.grade = grade;
}
public void setAge(int age) {
this.age = age;
}
public String getName(Student a) {
return a.name;
}
public int getAge(Student a) {
return a.age;
}
public int getGrade(Student a) {
return a.grade;
}
#Override
public String toString(){
return "Student(name:" + name + ", age:" + age + ", grade:" + grade + ")";
}
}
This code is kind of messy because you include some code that shouldn't appear in Student class. For example, the addStudent method is not static and in order to call it, you need to first instantiate an instance of Student and call the method on it. However, the method is trying to ask user to input the information of a new Student instance, which is a bad design.
So, keep the Student class only do what it should do. For your case, Student only need to store its age, grade and name fields and define constructors to initialize these fields, and optional getter and setter methods to set and retrieve these fields upon your needs.
You will need a 'manager' class which manages your application. This class will keeps track of a list of students, and asks users to input information of a new student and then initialize the student instance and put it in the list. This Manager class can even manage an UI which you need to take user input or display information to the user. So, it will be this class's responsibility to provide a addStudent method.
Student class itself should know nothing about your application's logic like it may be a course selection program or something else. It only manages its own information while some manager class will take care of the application's logic.
I have been set an assignment to create a small register based program written in Java, in the form of a linked list. I started by creating a student class, and then a tester file for the class. Following that, in the registry file I have set out my methods, and a constructor, and am in the process of writing a tester file to test all my methods.
However I am having trouble when trying to remove a specific element from my linkedlist, I want to be able to remove a student, referencing them by their individual studentID, but am not sure how to do this.
Whilst trying to solve the problem I came across the removeFirstOccurrence(Object o) method. Is this the right method to use?
Any help would be much appreciated.
STUDENT FILE CODE:
public class Student {
private String foreName;
private String surName;
private int studentID;
//declaring the variables needed for my student
public Student (String foreName, String surName, int studentID)
{
this.foreName = foreName;
this.surName = surName;
this.studentID = studentID;
}
//constructor to set out what a student needs
public String getForeName() {
return foreName;
}
public String getSurName() {
return surName;
}
public int getStudentID() {
return studentID;
}
public void setForeName(String foreName) {
this.foreName = foreName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
// getters and setters for my variables
public String toString ()
{
return getClass().getName() + "foreName = " + foreName + "surName = " + surName + "studentID = " + studentID;
}
//my toString method
}
REGISTRY FILE CODE:
import java.util.*;
public class Registry {
LinkedList<String> studentList
= new LinkedList<String>();
//setting my type parameter
public Registry() {}
//empty constructor to hold arguements
public void addStudent(String aStudent)
{
this.studentList.addLast(aStudent);
}
public void deleteStudent(int studentID)
{
//????
}
#Override public String toString()
{
return "Registry";
}
public String format()
{
}
REGISTRY TESTER FILE CODE:
import java.util.*;
public class RegistryTester {
public static void main (String[] args)
{
LinkedList<String> studentList
= new LinkedList<String>();
System.out.println("Test 1");
System.out.println("Methods tested: addStudent, constructor");
System.out.println("********************");
studentList.add("Joe Perkins 123");
studentList.addLast("Shilpa Gupta 1234");
studentList.addLast("Seany Ray 12345");
// adding 3 students to my list
System.out.println(studentList);
}
}
Define the List as a List of Student
LinkedList<Student> studentList = new LinkedList<Student>();
Override the hashCode() and equals() method in Student class.
public boolean equals(Object obj) {
if (obj instanceof Student) {
return studentID == ((Student)obj).getStudentID();
}
return false;
}
public int hashCode() {
return studentID;
}
Define methods:
public void addStudent(Student aStudent)
{
this.studentList.addLast(aStudent);
}
public void deleteStudent(Student astudent)
{
this.studentList.remove(aStudent)
}
First you should make your LinkedList for type Student:
LinkedList<Student>
Then to remove a student, you could :
go through the list, find out the student object with same id, remove it
override equals() and hashcode() method in your Student class, then
public void deleteStudent(int studentID)
{
//getStudent object (stu) By the given ID
studentList.remove(stu);
}
use Map, (HashMap or LinkedHashMap) instead of LinkedList, key is the studentId, value is the studentObject. This will make add/remove easier.
If you have a Collection (in your case a LinkedList) of Students and call remove(studentToRemove) on it, Java will compare each object with studentToRemove by using its equals() method.
In your case, you haven't written an equals() method, hence the one for Object is used. If indeed a student is uniquely identified by its studentId (that is, two Student instances with the same studentId are always the same student) you should override the equals() metod and check for equality using that field.
Read about equals() and hashCode().
Another alternative would be to iterate the list until you find the match, and then remove the student from the list.