Java calling an object into an arraylist of another class - java

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

Related

So I am lost in creating classes, private/public variables, get/set functions, and more in Java

So this is the first part of my assignment:
Create a new java class called "House".
Add constructor without parameters and add a system out put of your choice
Add 4 Private Member Variables
an integer that represents the number of rooms
a String that represents the address
a boolean that represents if the house is for sale
a double that represents the value of the house
Add a Get and Set functions for ALL 4 member variables
In my house code I think this is the right way to do it:
public class House {
private int Rooms;
private String Address;
private double Value;
private boolean Sale;
public House() {
System.out.println("CONSTRUCTOR EXECUTED");
}
public void setRooms(int Rooms) {
this.Rooms = Rooms;
}
public int getRooms () {
return Rooms;
}
public void setAddress (String Address){
this.Address = Address;
}
public String getAddress() {
return Address;
}
public void getValue(double Value) {
this.Value = Value;
}
public double setValue() {
return Value;
}
public void getSale(boolean Sale) {
this.Sale = Sale;
}
public boolean getSale() {
return Sale;
}
}
For the second part, which I'm more confused about, is says this:
Create a Main Class and add the static main function
Initialize Main and add a start function
In the start function create new House object
Call all 4 Set functions
Output all 4 Get Functions
Example Output "The House has '4' rooms located at 'address' and is or is not for sale'
If the house is for sale, out the value of the house
So I created the Main file and I think I have the start up correct but I don't know how to print it all out. This is what I at least have so far:
public class Main {
public static void main(String[] arg) {
}
private void start() {
House rooms = new House ();
}
}
I definitely do not want the answer, just some pointers in the right direction.
Looking at the instructions, I don't think you need to create a separate Main class. I think when it says 'Initialize Main' it just means add the main method to the House class.
Additionally, the way you have it now is not going to work properly. start() will not be able to be called from the main method, since main is static and start is not.
My feeling is that the best way to go about it would be to put main and start in the House class. Then, you can initialize an instance of House in the main method, and then call start on that instance. From there, start can perform the rest of the instructions.
Hope this helps.

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.

Printing address instead of array elements? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
So in my code, I made a class named Pet, that would have both a default constructor and a non-default constructor that passes in String name, and int age of the pet.
public class Pet
{
// instance variables
private int age;
private String name;
/**
* Constructor for objects of class Pet
*/
public Pet()
{
// initialise instance variables
age = 0;
name = "somePet";
}
public Pet(int age, String name)
{
this.age = age;
this.name = name;
}
}
Then I created a class named petArray that would add to the array and print out the array...
public class PetArray
{
// instance variables
private Pet [] petArray;
/**
* Constructor for objects of class PetArray
*/
public PetArray()
{
// initialise instance variables
petArray = new Pet[5];
}
public void addPets()
{
// put your code here
Pet myPet = new Pet(4, "Spots");
petArray[0] = (myPet);
petArray[1] = new Pet(2, "Lucky");
petArray[2] = new Pet(7, "Joe");
}
public void printPets()
{
for (int i = 0; i < petArray.length; i++)
{
System.out.println(petArray[i]);
}
}
}
But then, I get this in the terminal window when trying to print it out...
Pet#13255e3c
Pet#171ac880
Pet#52185407
null
null
You forgot to override toString() method inherited from Object.
In this case you can use something like this:
#Override
public String toString() {
return (name + age);
}
Java compiler just does not know how to print it, you have to inform it :)
In your addPets() method you are only adding 3 objects to your petArray while there are 2 more spaces you need to fill as you declared that array to be a length of 5.
You could change the length of your array down to 3 or you could add 2 more objects, that should fix your problem.
And as stated above, adding the toString method will get rid of the addressing issues.
class Pet {
...
#Override
public String toString(){
// the string passed from here will be shown in console
}
}
Your output is fine according to your code. You have to override toString() method to print as per your requirement. Add this may be it will help.
#override
public string toString(){
return "your required string"; // i.e : name or name+age
}

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.

Printing a list array which uses threads to a text area in java

I am having problems storing and printing a list array which uses threads. I want to store the list of threads in a list array and print them to a text area where they can be sorted by a user. The code below is my array class and transaction class.
import java.util.ArrayList;
/**
* #author B00533474
*/
public class Array {
ArrayList<Transaction> transactionList = new ArrayList<Transaction>();
// Variables
private final Transaction nextTransaction;
public static int inInt2 = TranAcc.inInt2;
public static int inInt3 = TranAcc.inInt3;
public static String inInt1 = TranAcc.inInt1;
//public static void main(String[] args){
public Array(){
nextTransaction = new Transaction(inInt1, inInt2, inInt3, 2000);
transactionList.add(nextTransaction);
transactionList.get(3);
}
/*public static void main(String[] args){
Array ar = new Array();
ar.add(nextTransaction);
}
*
*/
}
The variables inInt1 etc are from another class called TranAcc which is the main GUI of my project.
package bankassig;
/**
*
* #author B00533474
*/
public class Transaction {
String type;
int amount;
int wkNum;
int balance;
public Transaction(String ty, int am, int wk, int bal)
{
type = ty;
amount = am;
wkNum = wk;
balance = bal;
}
}
My problem is actually implementing/using the list area, I was going to add an action listener to a button on a gui which would call the list area and print the transactions in a text are but I was unsure of the code to write for this ( I know about the action listener just not calling the list array).
Any help would be much appreciated and if I need to provide anymore code I would be happy to do so.
How do I implement the list array and use it to print out the values of the variables which I used?
Overwrite the inherited (from java.lang.Object) toString() method in your Transaction class. In your toString() method, you can put together a String with your variable data in any format that makes sense to a user, and return it. You can then iterate through all the Transactions in your Array class's list, call the toString() method, and put it in your GUI. Something like:
for (Transaction trans : yourArrayObj)
{
yourTextArea.append(trans.toString());
}

Categories