Array object and element? - java

this class works:
public class Undergrad extends Student{
private int year;
private int numOfCourses=0;
private Course[] courses=new Course[4];
public Undergrad(int year,String name,String major,double gpa){
super(name,major,gpa);
this.year=year;
}
public int getYear(){
return year;
}
public void setYear(int year){
this.year=year;
}
public String getName(){
return name;
}
public String getMajor(){
return major;
}
public double getGpa(){
return gpa;
}
public void setGpa(double gpa){
this.gpa=gpa;
}
public Course[] getCourses(){
return courses;
}
public void addCourses(Course course){
if(numOfCourses>=4){
System.out.println("Student can not study");
} else{
courses[numOfCourses]=course;
numOfCourses++;
}
}
public void printCourses(){
for(int i=0;i<numOfCourses;i++){
System.out.println(courses[i].toString());
}
}
public String toString(){
return "Student name"+name+"courses"+numOfCourses;
}
}
but I was just wondering shouldn't "course" have an "s" so it becomes courses, so it can become the same as the name in the array "courses". Also is the printCourse method the same as the System.out.print method?
public void addCourses(Course course)

Course is simply the name of the class. Even if there are plenty of Course objects, the name stays the same.
As of courses is the name of the object's reference so you're free to choose it while creating it.
If your question is why in addCourses(Course course) course does not have an s, it is because it is a reference to a Course object and not to the array.
courses[numOfCourses]=course
Here, we're adding course to the courses array of Course objects.

To your question, it doesn't really make any difference. Your 'addCourses' method is not a setter or getter method, so should in future you want to use the class for any purposes that imply serialization you will be fine.
But just for readability you could rename it to void addCourse(Course c).
In addition, you could guard against potential null argument using the Optional class added in Java 8.
public void addCourse(Course c){
if(numOfCourses>=4){
System.out.println("Student can not study");
} else{
courses[numOfCourses]=Optional.ofNullable(c).orElse(new Course(argument 1, argument 2, argument etc));
numOfCourses++;
}
}

Related

Why do I keep getting a Null Exception Error?

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.

Print the value of a Java constructor

I am a java beginner and I am trying to get used to objects. Is there anyway that I can print out the value of a constructor in main? How can I print out the value's Kevin,20? Thanks
public class MainConstructor {
public static void main(String[] args) {
ConstructorClass emp1 = new ConstructorClass("Kevin", 20);
}
}
//Constructor Class
public class ConstructorClass {
private String name;
private int number;
public ConstructorClass(String name, int number) {
this.name = name;
this.number = number;
System.out.println("called");
}
}
Add a toString() method to ConstructorClass:
public String toString() {
return name + "," + number;
}
Then call this from main:
public static void main(String[] args) {
ConstructorClass emp1 = new ConstructorClass("Kevin",20);
System.out.println(emp1.toString());
}
Try using toString() in your class
public String toString() {
return this.name + "," + this.number;
}
and in your main just do emp1.toString(); to print it to your console
Constructor is basically just another method (but for the love of what is holy, never say that during interview or even to your professor) so there is nothing wrong with doing this:
public class ConstructorClass {
private String name;
private int number;
public ConstructorClass(String name, int number) {
this.name = name;
this.number = number;
System.out.println(name+" "+number);
}
}
But this solution is really ugly and kind of "hotfixy". Better solution would be to have constructor to only get the values and have separate method to print what you want:
public ConstructorClass(String name, int number) {
this.name = name;
this.number = number;
}
void printNameAndNumber() {
System.out.println(name+" "+number);
}
And use the class like this in your main
ConstructorClass c = new ConstructorClass("John",85)
c.printNameAndNumber();
Also some people like to handle this by going through hoops and loops and overriding ToString, but that is being too overzealous and there is really no benefit in your case (or any other primitive case).
public ConstructorClass(String name, int number) {
this.name = name;
this.number = number;
System.out.println(name + "," + number);
}
If you want to properly print out those values, you should have getter methods set in your methods
Example below
public String getName(){
return name;
}
public int getNumber(){
return number;
}
Then to print those values, you should then use methods toString() and method print() to display your values
Example
public String toString(){
return getName() + " " + getNumber();
}
public void print(){
System.out.println(toString());
}
Then in the class with the main method, you call your print method for that specific class
Example
ConstructorClass emp1 = new ConstructorClass("Kevin",20);
emp1.print();
Hope this helped, Enjoy :)

Full access to class's elements , which contain into other class

I think it's normal desire to have access for manipulating with data. Should i create getters/setters in Record class, if i already use Storage for this goal, made on Record? Or what need to do?
public class Storage {
List<Record> record;
public Storage(){
this.record = new ArrayList<Record>();
}
public void addRecord(Record record) {
this.record.add(record);
}
public Record getRecord(int number){
return this.record.get(number);
}
public class Record {
private int number;
private int count;
private Object code;
/* public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
} */
public Record(int number, int count, Object code) {
this.number = number;
this.count = count;
this.code = code;
}
#Override
public String toString() {
return (this.number+" "+this.code+" "+ this.count);
}
}
According to me it is not require to write setter and getter methods until you don't want to modify them.In your code you have initialized fields in constructor and overridden toString() method to get meaningful content of Record object and never trying to modify Record 's fields directly.
I strongly feel that it is not required.

Having trouble removing a specific element from a linked list

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.

How to sort list which having variable as list

I have class ABC
class ABC{
private List<XYZ> xyzList -- Though its list it contains single object;
private String txt;
}
class XYZ{
private long price;
}
I want to sort List abcList based on class XYZ price variable.
Please provide best possible approach for sorting in ascending order.
Have you tried one of these methods:
java.util.Collections.sort(List<T>)
Or
java.util.Collections.sort(List<T>, Comparator<? super T>)
One way is implement Comparable interface in XYZ and override compareTo and then Collections.sort(yourListOfXYZ) will sort the list.
Other way is using Comparator.
Collections.sort(xyzList, new Comparator<XYZ>() {
#Override
public int compare( XYZ e1,XYZ e2) {
return Long.valueOf(e1.getPrice()).compareTo(Long.valueOf(e2.getPrice()));
}
});
Try this
Collections.sort(xyzList);
I would suggest you look into the documentation for the Comparable interface. Possible even with the use of an PriorityQueue.
In you case you either need to make XYZ implement Comparable, provide a Comparator<XYZ> or a simpler option is to unwrap it and just use a List<Double> or a SortedSet<Double> to hold you prices.
Sample code from http://java2novice.com/java-collections-and-util/arraylist/sort-comparator/
public class MyArrayListSort {
public static void main(String a[]){
List<Empl> list = new ArrayList<Empl>();
list.add(new Empl("Ram",3000));
list.add(new Empl("John",6000));
list.add(new Empl("Crish",2000));
list.add(new Empl("Tom",2400));
Collections.sort(list,new MySalaryComp());
System.out.println("Sorted list entries: ");
for(Empl e:list){
System.out.println(e);
}
}
}
class MySalaryComp implements Comparator<Empl>{
#Override
public int compare(Empl e1, Empl e2) {
if(e1.getSalary() < e2.getSalary()){
return 1;
} else {
return -1;
}
}
}
class Empl{
private String name;
private int salary;
public Empl(String n, int s){
this.name = n;
this.salary = s;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String toString(){
return "Name: "+this.name+"-- Salary: "+this.salary;
}
}

Categories

Resources