Adding member objects to ArrayList<Membership> - java

I am trying to complete a program to help me learn java before we do it in class. But I am stuck trying to add a Member to the club, print it out and then count the number of members. I do not know where to start after I have added the basics into the code.
I am new to stack overflow and do not know how to format correctly so I am sorry. :)
Any tips and help would be greatly appreciated.
Thanks
package lab8.club;
import java.util.ArrayList;
public class Club
{
ArrayList<Membership> members;
/**
* Constructor for objects of class Club
*/
public Club()
{
members = new ArrayList<Membership>();
// Initialise any fields here ...
}
/**
* Add a new member to the club's list of members.
* #param member The member object to be added.
*/
public void join(Membership member)
{
members.add(member);
}
/**
* #return The number of members (Membership objects) in
* the club.
*/
public int numberOfMembers()
{
return members.size();
}
public static void main(String args[]){
Membership member1 = new Membership("test", 1, 2011);
System.out.println();
}
}
package lab8.club;
public class Membership
{
// The name of the member.
private String name;
// The month in which the membership was taken out.
private int month;
// The year in which the membership was taken out.
private int year;
public Membership(String name, int month, int year)
throws IllegalArgumentException
{
if(month < 1 || month > 12) {
throw new IllegalArgumentException(
"Month " + month + " out of range. Must be in the range 1 ... 12");
}
this.name = name;
this.month = month;
this.year = year;
}
public String getName()
{
return name;
}
public int getMonth()
{
return month;
}
public int getYear()
{
return year;
}
public String toString()
{
return "Name: " + name +
" joined in month " +
month + " of " + year;
}
}
package lab8.club;
public class ClubDemo
{
// instance variables - replace the example below with your own
private Club club;
/**
* Constructor for objects of class ClubDemo
*/
public ClubDemo()
{
club = new Club();
}
/**
* Add some members to the club, and then
* show how many there are.
* Further example calls could be added if more functionality
* is added to the Club class.
*/
public void demo()
{
club.join(new Membership("David", 2, 2004));
club.join(new Membership("Michael", 1, 2004));
System.out.println("The club has " +
club.numberOfMembers() +
" members.");
}
}

Your code is actually ok. What you really need is a main method to start the execution of your code. Create a new class such as the following Demo.java:
public class Demo {
public static void main(String[] args) {
ClubDemo demo = new ClubDemo();
demo.demo();
}
}
Output:
The club has 2 members.
You will see that in ClubDemo's demo() method that members are added via club.join which calls the ArrayList.add method to add member objects to the members ArrayList.
For more information about the main method signature, see the Java Hello World Tutorial:
In the Java programming language, every application must contain a
main method whose signature is:
public static void main(String[] args)
The modifiers public and static can be written in either order (public
static or static public), but the convention is to use public static
as shown above. You can name the argument anything you want, but most
programmers choose "args" or "argv".

In main I think you can just call Club club = new Club() to create a new Club object, then simply call club.join(member1) to add your new member into the club.
I would suggest changing the method name join because when you're reading the code, it's not really right that the CLUB is joining a MEMBER. It should be the other way around so unless you need to, I'd just take out the method and just use the ArrayList's add.
And lastly, if you want to use your join method (and not the ArrayList's add), I would consider setting members in Club to be private.

Related

Wants static but can't support?

I am trying to create a random car generator that also displays info. I thought I had everything until the randomCar portion. It says that
'com.company.Main.this' cannot be referenced from a static context
under the return statements in the switch. Any thought on to where I may be going wrong?
package com.company;
public class Main {
class Car{
private String name;
private boolean engine;
private int cylinders;
private int wheels;
public Car(String name){
this.name = name;
}
public String getName(){
return name;
}
public int getCylinders() {
if(cylinders == 0){
System.out.println("Unknown amount of cylinders");
}
return cylinders;
}
public int getWheels() {
return wheels;
}
public boolean isEngine() {
return engine;
}
}
class Tacoma extends Car{
public Tacoma(String name) {
super("Tacoma");
}
public boolean isEngine(boolean engine) {
return true;
}
public int getCylinders(int cylinders) {
return 6;
}
public int getWheels(int wheels) {
return 4;
}
}
class Motorcycle extends Car{
public Motorcycle(String name) {
super("Harley Davidson");
}
public boolean isEngine(boolean engine) {
return true;
}
public int getCylinders(int cylinders) {
return 2;
}
public int getWheels(int wheels) {
return 2;
}
}
class Volvo extends Car{
public Volvo(String name) {
super("Volvo");
}
public boolean isEngine(boolean engine) {
return true;
}
public int getCylinders(int cylinders) {
return 4;
}
public int getWheels(int wheels) {
return 4;
}
}
public static void main(String[] args) {
for (int i = 1; i<6; i++){
Car car = randomCar();
System.out.println("Car # " + i + ":" + car.getName() + "\n" +
"Number of cylinders: " + car.getCylinders() + "\n" +
"Number of wheels: " + car.getWheels()+ "\n" +
"Engine is: " + car.isEngine());
}
}
private static Car randomCar() {
int randomNumber = (int) (Math.random()*5) +1;
System.out.println("Random number generated is: " + randomNumber);
switch (randomNumber){
case 1:
return new Tacoma(); // This is where I am getting an error
case 2:
return new Motorcycle(); // This is where I am getting an error
case 3:
return new Volvo(); // This is where I am getting an error
}
return null;
}
}
I would start by reading here: https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html -> actually all the chapters there would be useful for you to read: https://docs.oracle.com/javase/tutorial/java/javaOO/index.html
Strictly speaking, to solve your "cannot be referenced from a static context" you can just make your classes static (Car, Tacoma, Motorcycle, Volvo) static class Car{
From my point of view you don't need nested classes, just create the classes in the same package as your Main class and you should be good to go (feel free to create more packages to better structure your classes)
Also I'm assuming your code is a work in progress because there are multiple issues with it:
methods like this don't make sense public boolean isEngine(boolean engine) {return true;} You receive a parameter that you ignore and you return a constant value: true; What I assume you want to do here is to have different types of cars each with its own predefined characteristics, but for that you should set the values for the attributes in the parent, Car. For this you either define protected setters, make the fields protected, or, best, create constructor which takes all the values
public Car(String name, boolean engine, int cylinders, int wheels) {
this.name = name;
this.engine = engine;
this.cylinders = cylinders;
this.wheels = wheels;
}
and you can have in Tacoma
public Tacoma(String name) {
super(name, true, 6, 4);
}
running your code I got the randomNumber 5 so that returned null and got a NPE, I assume work in progress
in your switch you are calling the default constructor new Tacoma() however that isn't available anymore since you defined a constructor with a parameter, use the available constructor or create the no-arg constructor.
There are other concerns regarding OOP principles so I recommend reading them again, just google "java OOP principles" and then "SOLID"... there are a lot of great resources out there, you just need time and patience and you'll get there!
When you put the Car class definition inside the class definition of Main, you made Car an inner class, so that a Car requires an outer class Main instance. In the static method there is no Main instance, and you can’t create the Car without it.
There is an immediate fix: add keyword static to the Car class:
static class Car {
which means there is no link to the enclosing object.
But there is no benefit here to making this a nested class, it would be better not to put one class definition inside another when you’re starting out.
The inner classes you've defined are instance members, meaning they belong to a specific instance of Main, and thus cannot be referenced from a static context that doesn't have a Main instance. The easiest way to resolve this would be to declare all the inner classes static.
First of all, to solve your error: 'com.company.Main.this' cannot be referenced from a static context, make all the methods static:
static class Car{//code here}
static class Volvo extends Car{//code here}
static class Tacoma extends Car{//code here}
static class Motorcycle extends Car{//code here}
Whenever you see that error, it means one static method is calling a non-static method. Therefore, just make both non-static or both static. The only exception is public static void main(String[] args); which must be static.
After solving the original errors, there is more to debug:
'Volvo(java.lang.String)' in 'com.company.Main.Volvo' cannot be applied to '()'
'Motorcycle(java.lang.String)' in 'com.company.Main.Motorcycle' cannot be applied to '()'
'Tacoma(java.lang.String)' in 'com.company.Main.Tacoma' cannot be applied to '()'
All this means is that your methods Tacoma(), Volvo(), and Motorcycle() require the parameter String name. So all you have to do is give them a name: here, it's
`new Tacoma("cool")`
new Volvo("car")
new Motorcycle("harley davidson")`
Finally, after solving the static and parameter problems, you are getting a NullPointerException, because randomCar() returns null. Your method says Car randomCar(), indicating it will return a Car, but then the return statement was return null;. Therefore, just return a Car - rtn here for our purposes:
private static Car randomCar() {
int randomNumber = (int) (Math.random()*5) +1;
System.out.println("Random number generated is: " + randomNumber);
Car rtn = null;
switch (randomNumber){
case 1:
rtn = new Tacoma("cool"); // This is where I am getting an error
case 2:
rtn = new Motorcycle("harley davidson"); // This is where I am getting an error
case 3:
rtn = new Volvo("car"); // This is where I am getting an error
}
return rtn;
}
This isn't all the debugging your code needs, but it's a start: here's what the system did so far:
Random number generated is: 3
Unknown amount of cylinders
Car # 1:Volvo
Number of cylinders: 0
Number of wheels: 0
Engine is: false
Random number generated is: 5
Hooray!
Did this help?

Why can't I seem to find the error in my program when compiling. Help needed

The pet store program should start with the user being able to choose to adopt a pet or give a pet the to the shop. If the user wants to adopt a pet, they should be able to see either all available pets, unless they say they know what type of pet they want, then show only available pets of that type.
The 4 methods that will need to be created for this program should:
add new pets
get a pet adopted
show pets by type
show pets available for adoption
Object Class: Pets.java
import java.util.*;
public class Pets {
public static void main(String[] args){
private double age; // age of the animal (e.g. for 6 months the age would be .5)
private String petName; // name of the animal
private String aType; // the type of the pet (e.g. "bird", "dog", "cat", "fish", etc)
private int collarID; // id number for the pets
private boolean isAdopted = false; // truth of if the pet has been adopted or not
private String newOwner;
private Date adoptionDate;
public double getAge() {
return age;
}
public void setAge(double age) {
this.age = age;
}
public String getPetName() {
return petName;
}
public void setPetName(String petName) {
this.petName = petName;
}
public String getaType() {
return aType;
}
public void setaType(String aType) {
this.aType = aType;
}
public int getCollarId() {
return collarID;
}
public void setCollarId(int collarId) {
this.collarID = collarId;
}
public boolean isAdoptated() {
return isAdopted;
}
public void setAdoptated(boolean isAdoptated) {
this.isAdopted = isAdoptated;
}
public Date getAdoptionDate() {
return adoptionDate;
}
public void setAdoptionDate(Date adoptionDate) {
this.adoptionDate = adoptionDate;
}
#Override
public String toString() {
return "Pets [age=" + age + ", petName=" + petName + ", aType=" + aType + ", collarId=" + collarID
+ ", isAdoptated=" + isAdopted + ", adoptionDate=" + adoptionDate + "]";
}
}
}
You should define the data fields and methods inside the class, but not inside the main()-method. The main()-method is the entry point of your java application and could be used to create an instance of your Pets class.
e.g.:
public static void main(String[] args) {
Pets pet = new Pets();
}
This code is not compiling for 2 main reasons:
You are specifying access modifiers on variables inside a method (in this case main), which is forbidden;
You are writing methods (e.g. getAge) inside another method (main) and trying to return a variable (e.g. age) that is out of that scope, in fact the variable age is not known inside the getAge method, because it's declared in the main method.
You should move the variable declaration to class level, and then have all methods separated using those variables. I'll give you a sketch, not the complete solution:
import java.util.*;
public class Pets {
/* Insert all variable declarations here */
private double age;
/* Constructor if you need it */
public Pets(/* parameters you think you need */) {
// Set attributes when you declare a new Pets()
}
/* Insert all methods you need here */
public double getAge() {
return this.age;
}
The positioning of the main method - for what I've understoon from your description - should be placed outside this class, in another class where the whole application will start to run. The Pet class should serve only for anything concerning pets (the four methods you will need to implement and all getters/setters for retrieving private class variables).
You’ve happened to put about everything — private fields and public methods — inside you main method. That doesn’t make sense. Everything that is in your main, move it outside, right under the line public class Pets {. That should fix your compiler error.

Java calling an object into an arraylist of another class

Okay, before anything, I would like to mention that this is for school so please DO NOT write any code that fixes my code as that will not teach me anything. Instead what I am looking for is references, explanations and proper terminologies if I use incorrect terminology.
So I am having a few issues here. Here is what I need to do,
*Include the following methods in the Student class:
a. an accessor (i.e., getter) for each instance variable from part B1
b. a mutator (i.e., setter) for each instance variable from part B1
Note: All access and change to the instance variables of the Student class should be through accessor and mutator methods.
c. constructor using all of the input parameters
d. print() to print specific student data (e.g., student ID, first name, last name) using accessors (i.e., getters)
Create a student Roster class with the following methods that contain all ArrayList method calls:
a. public static void remove(String studentID) that removes students from the roster by student ID
Note: If the student ID doesn’t exist, the method should print an error message indicating that it is not found.
b. public static void print_all() that prints a complete tab-separated list of student data using accessor methods
Note: Tabs can be formatted as such: 1 [tab] First Name: John [tab] Last Name: Smith [tab] Age: 20 [tab] Grades: {88, 79, 59}. The print_all() method should loop through all the students in the student array list and call the print() method for each student.
c. public static void print_average_grade(String studentID) that correctly prints a student’s average grade by student ID
d. public static void print_invalid_emails() that verifies student e-mail addresses and displays all invalid e-mail addresses to the use*
That above is where I am having trouble, The arraylist, the constructor and calling the Student class in the Roster class.
here is my code.
Student Class
/**
* Write a description of class Student here.
*
* #author (Richard Talcik)
* #version (v1 3/5/17)
*/
public class Student {
// initialize instance variables
private String csFirstName; //I am using cs infront of the name because this is a class variable and a string
private String csLastName;
private String csEmail;
private int ciAge;
private int ciStudentID;
private int[] ciaGrades; //cia for class, integer, array;
public Student(String sFirstName, String sLastName, String sEmail, int iAge, int iStudentID, String[] grades) {
//doing the consturctor
this.setFirstName(sFirstName);
this.setLastName(sLastName);
this.setEmail(sEmail);
this.setAge(iAge);
this.setStudentID(iStudentID);
this.setGrades(grades);
}
/**he methods to get and then followed by set
*/
public String getFirstName()
{
// put your code here
return csFirstName; //returning the value of the first name when called.
}
public String getLastName()
{
// put your code here
return csLastName;
}
public String getEmail()
{
// put your code here
return csEmail;
}
public int getStudentID()
{
// put your code here
return ciStudentID;
}
public int getAge()
{
// put your code here
return ciAge;
}
public int[] getGrades()
{
// put your code here
return ciaGrades;
}
// calling the sets from here on out
public void setFirstName(String newFirstName)
{
// put your code here
csFirstName = newFirstName;
//setting it
}
public void setLastName(String newLastName)
{
// put your code here
csLastName = newLastName;
//setting it
}
public void setEmail(String newEmail)
{
// put your code here
csEmail = newEmail;
//setting it
}
public void setAge(int newAge)
{
// put your code here
ciAge = newAge;
//setting it
}
public void setStudentID(int newStudentID)
{
// put your code here
ciStudentID = newStudentID;
//setting it
}
public void setGrades(int[] newGrades)
{
// put your code here
ciaGrades = newGrades;
//setting it
}
}
This roster class is asking me to add arguments when I call Student stu = new Student(); But I don't understand what arguments to add into there?
I also dont really understand how I am going to incorporate my arraylist to add my methods in there from the student class? (sorry if i used wrong terminology, please correct me if needed)
Roster Class
import java.util.ArrayList;
/**
* Write a description of class Roster here.
*
* #author (Richard Talcik)
* #version (v1)
*/
public class Roster {
// instance variables - replace the example below with your own
/**
* Constructor for objects of class Roster
*/
public static void main(String args[]) {
Student stu = new Student("John", "Smith", "John1989#gmail.com", 20, 1, Grades[1]);
ArrayList<Student> myRoster = new ArrayList<Student>();
myRoster.add(new Student("Suzan", "Erickson","Erickson_1990#gmailcom", 19, 2, [91,72,85]));
}
public static void remove(String studentID)
{
// put your code here
}
public static void print_all()
{
//do something
}
public static void print_average_grade(String studentID)
{
//do something
}
public static void print_invalid_emails()
{
//do something
}
}
please any tutorials that will help explain this will be well worth it.
Also, I work third shift and my school is fully online. My mentor isn't or tutor isn't available during the hours that I am awake and emails are not really best method of communication as it takes days for a response.
Firstly for a beginner, not bad :)
However when using the ArrayList object type in java, the type of the list must be of the object you whish to put inside the ArrayList, i.e. if you want to keep a list of students, then you have to write it as
AssrayList<Student> = new ArrayList<Student>();
you can also specify the size of the list as a param, but remember, ArraList grows dynamically as things are added and removed from the list.
As far as you Constructor goes, you have to add the variables you assign values to on the inside as the params of the constructor. also the question states that you have to access all class objects with the use of their accessor and mutator methods, having that the current way you have your constructor at the moment is incorrect as you are directly assigning values to the class onjects of Student, you can change that to be similar to the following:
constructor (paramType param) {
mutatorMethod(param)
}
so your constructor should be in the lines of
Student(String name, String surname) {
setName(name)
setSurname(surname)
}
Hope this helps :)
You have written Student class with a constructor that takes parameters. So, in Roaster class you have to call matching constructor of Student class. My guess is that you did not quite understand my answer.
I would suggest look for a java tutorial on oracle site and even better if you can get a copy of this book called The java programming language

How do I create an object from another class (BlueJ)

I am making a program that simulates a Store and a Member. I am trying to write a method, memberRegister2(). This method is the the Store class but calls the constructor from the Member class to make a member object. This method is to be passed the name, id and pinNumber as parameters and then creates the Member object, which is to be stored in a local variable 'member'. I have no idea how to do this. As you will see from the code below I have tried to use the 'Member member = new Member()' But i do not know how to make the parameters user input.
(P.S I am using BlueJ)
Here is my code for both classes hopefully making my question make more sense. I am very new to java so excuse bad coding.
public class Store
{
// instance variables
private String storeName;
private int total;
//Member member;
/**
* Constructor for objects of class Store
*/
public Store(String newStoreName, int newTotal)
{
// initialise instance variables
storeName = newStoreName;
total = newTotal;
}
//Accessor Methods
public String getStoreName()
{
return storeName;
}
public int getTotal()
{
return total;
}
public void memberRegister1(Member newMember)
{
System.out.println("Salford Thrifty " + storeName + ": Welcome " + newMember.getName() + " (id:" + newMember.getId() + ")" );
}
public void memberRegister2()
{
//Member member = new member(memberName, memberId, memberPinNumber);
}
//Mutator Methods
public void newStoreName(String newName)
{
storeName = newName;
}
public void newTotal(int newTotal)
{
total = newTotal;
}
}
and the Member class
public class Member
{
// instance variables
private String name;
private String id;
private String pinNumber;
/**
* Constructor for objects of class Member
*/
public Member(String memberName, String memberId, String memberPinNumber)
{
// initialise instance variables
name = memberName;
id = memberId;
pinNumber = memberPinNumber;
}
public Member()
{
// initialise instance variables
name = "Bob";
id = "ASD123";
pinNumber = "5678";
}
//Accessor Methods
public String getName()
{
return name;
}
public String getId()
{
return id;
}
public String getPinNumber()
{
return pinNumber;
}
//Mutator Methods
public void newName(String newMemberName)
{
name = newMemberName;
}
public void newId(String newMemberId)
{
name = newMemberId;
}
public void newPinNumber(String newMemberPinNumber)
{
name = newMemberPinNumber;
}
}
I have been told to keep the variable at the top private and use pointers? Not sure what this means but it has not been explained to me very well.
You can a Scanner to read the user's input like so.
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
Then just initialize your member instance using the strings entered by the user.
String memberName, memberId, memberPin;
Scanner s = new Scanner(System.in);
System.out.println("Enter a name");
memberName = s.nextLine();
System.out.println("Enter an id");
memberId = s.nextLine();
System.out.println("Enter a pin");
memberPin = s.nextLine();
Member m = new Member(memberName, memberId, memberPin);
Also, you probably want to make pin, and maybe the id ints instead of strings.
Here's something I have from an old class that should show you how:
SavingsAccount myAccount = new SavingsAccount(200, 5);
So when you want to create an object from another class you have to use that second class to initialize it as shown above the SavingsAccount is like int it instantiates the object and then the two integers SavingsAccount(200, 5); is used because the method within the second class is instantiated with two integers of its own so the object you are creating must have two integers of its own. And what I mean by the method has two integer instantiated is as shown in the code below:
public SavingsAccount(double amount, double rate)
{
super(amount);
interestRate = rate;
}
if you do not instantiate a method with two objects within the parentheses then you do not need them within:
SavingsAccount myAccount = new SavingsAccount(200, 5);
I hope this helps any with your question i'm fairly new myself and am trying to help with as much as I can My course uses BlueJ as well and I know a good bit about BlueJ so I hope this helps.

Implementing Enumerations interface to Print a class Object

This is my source code. I want to traverse a Vector using the Enumeration interface. If I simply traverse the Vector, I get hash codes of objects and if I implement interface Enumeration on the class Student I'm asked to override the nextElement() method. Can anyone tell me a way of overridding this method so that I get elements of class (i.e. name, r_num and cgpa) and not the hashcodes of objects?
import java.util.*;
public class Student implements Enumeration {
private String name;
private int r_num;
private float cgpa;
Student() {
}
Student(String name,int r_num,float cgpa)
{
this.name=name;
this.r_num=r_num;
this.cgpa=cgpa;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the r_num
*/
public int getR_num() {
return r_num;
}
/**
* #param r_num the r_num to set
*/
public void setR_num(int r_num) {
this.r_num = r_num;
}
/**
* #return the cgpa
*/
public float getCgpa() {
return cgpa;
}
/**
* #param cgpa the cgpa to set
*/
public void setCgpa(float cgpa) {
this.cgpa = cgpa;
}
public static void main(String[] args){
Vector<Student> studentList = new Vector<>();
Enumeration en;
System.out.println("Enter Students' Name, Roll Number and CGPA");
Scanner in= new Scanner(System.in);
char ch;
do
{
int x=0;
String s= in.next();
int r= in.nextInt();
float c= in.nextFloat();
studentList.add(new Student(s,r,c));
System.out.println("Enter another student's record?(y/n)");
ch= in.next().charAt(0);
}
while(ch=='y'|| ch=='Y');
System.out.println("List of Students: ");
en = studentList.elements();
while(en.hasMoreElements()){
System.out.println(en.nextElement());
}
}
#Override
public boolean hasMoreElements() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public Object nextElement() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
I want to traverse a Vector using the Enumeration interface.
No, you don't. You want to traverse a List, quite possibly an ArrayList, using the Iterable and Iterator interfaces. Vector and Enumeration are very old fashioned and almost certainly not what you want.
If I simply traverse the Vector, I get hash codes of objects.
No, you don't. You get the actual objects. The problem is, your class doesn't override the toString() method, so when you print them out with System.out.println you get the default toString() format of java.lang.Object, which looks like Student#DEADBEEF.
Add a toString() method to Student, such as:
#Override
public String toString() {
return name + " " + r_num + " " cgpa;
}
If you really want to implement Enumeration, take a look at the source code that comes with the JDK to see how classes like Vector and ArrayList implement it. But it doesn't make sense to have Student implement it, since a Student isn't a collection of anything that you can enumerate.
It looks like your problem is that you didn't override toString(), and so the call to print out the next element is using the default toString(), which prints out a relatively unhelpful message (i.e. the "hashcode" you're referring to, or the class name, an at sign, and the location of the object in memory).
Furthermore, you shouldn't be implementing Enumeration if your Student class does not represent something which can be iterated over.

Categories