Creating an object and calling it - java

this is my current code to store rooms(it compiles fine) but in the UML there is a variable called addEquipment and there is also another class called Equipment to be defined. I'm having trouble wrapping my head around what I'm supposed to do with this. Am I supposed to create and call an object called Equipment? what goes in addEquipment?
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private String equipmentList;
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public String getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(String anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
}
//Create room object
public Room(int capacity, String equipmentList) {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
return "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
}
}

You can create a new class Equipment and modify your attribute equipmentList to be a List:
public class Equipment {
private String name;
public Equipment(String name) {
this.name = name;
}
}
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private List<Equipment> equipmentList = new ArrayList<Equipment>();
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public List<Equipment> getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(List<Equipment> anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
Equipment oneEquipment = new Equipment(newEquipment);
equipmentList.add(oneEquipment);
}
//Create room object
public Room() {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
String capacity=String.valueOf(getCapacity());
String room = "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
return room;
}
}
In the method addEquipment, you can create a new Equipment and add it to equipmentList, like code above.

An Equipment class could be anything. Lets assume the "Equipment"-class has a String called "name" as it's attribute
public class Equipment {
String name;
public Equipment( String name) {
this.name = name;
}
public String getName() {
return this.name
}
}
When you extend your Room class by the requested "addEquipment" method, you can do something like this.
public class Room {
... // Your code
private int equipmentIndex = 0;
private Equipment[] equipment = new Equipment[10]; // hold 10 Equipment objects
public void addEquipment( Equipment eq ) {
if ( equipmentIndex < 10 ) {
equipment[ equipmentIndex ] = eq;
equipmentIndex++;
System.out.println("Added new equipment: " + eq.getName());
} else {
System.out.println("The equipment " + eq.getName() + " was not added (array is full)");
}
}
}
Now when you call
room.addEquipment( new Equipment("Chair") );
on your previously initialized object of the Room-class, you will get
"Added new equipment: Chair"
Hope this helps a bit.
PS: The code is untestet (maybe there hides a syntax error somewhere)

Related

Returning an object corresponding to a class

So i have 2 classes, and in the class race i have a method ( public Athlete getAthlete(int codAthlete) ) that
should return the object corresponding to the Athlete with the code passed by parameter, but i am not sure how to
implement it. Can someone give me a hand?
public class Athlete {
private int codAthlete;
private String name;
public Athlete(int codAthlete){
this.codAthlete = codAthlete;
}
public int getCodAthlete() {
return this.codAthlete;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public String getInformation() {
return "Code: " + this.codAthlete +
" Name " + this.name;
}
}
.
public class Race {
private String idRace;
private Set<Athlete> athletes;
public Race(String idRace) {
athletes = new HashSet<>();
this.idRace = idRace;
}
public String getIdRace () {
return this.idRace;
}
public Athlete getAthlete(int codAthlete){
for(Athlete a: Athlete){
if(a.getCodAthlete() == codAthlete)
a.getInformation();
}
return (????);
// Returns the object corresponding to the Athlete with the code passed by parameter.
}
}

UML with subclasses

public class Student {
private String name;
private long id;
private String grade;
private int[] test;
private int NUM_TESTS;
public Student(){
name="Un";
id=0;
grade="Un";
test=new int[0];
NUM_TESTS=5;
}
public Student(String x, long z) {
name=x;
id=z;
}
public void setName(String n) {
name=n;
}
public void setID(long i) {
id=i;
}
public void setGrade(String g) {
grade=g;
}
/*public void setTestScore(int t,int s) {
test=t;
test=s;
}
public int getTestScore(int) {
return test;
}*/
public int getNumTests() {
return NUM_TESTS;
}
public String getName() {
return name;
}
public long getID() {
return id;
}
public String getGrade() {
return grade;
}
public String toString() {
return getTestScore()+getNumTests()+getName()+getID()+getGrade();
}
/*public void calculateResult() {
int sum=0;
for (int t:test)sum+=t;
double average= 1.0t*sum/5;*/
}
}
Here is my code I have spaced out the places where I am having the issues. I am writing a Student subclass with subclasses undergrad and postgrad.
Here is the UML
I don't understand how to correctly implement testScore if it is not one of the variables? Nevermind the calculate result I'll fix that myself. I am also unsure if my constructors are accurate. All the students do five exams that's a constant
setTestScore(int t, int s)... I do recommend to use carefully chosen names (identifiers). For example if you just rename the parameters to: setTestScore(int testNumber, int score) you can be more familiar what should you inplement.
test = new int[0];isn't what you want. You want test = new int[NUM_TESTS]
Try to reconsider method setTestScore(int testNumber, int score)
first parameter is actually the index in the array of test and the second is the value.
So, your method should be something like this:
public void setTestScore(int testNumber, int score) {
test[testNumber] = score;
}
I just gave you some guidance for your own implementation...
First of all, It seems that Student class should be abstract. because each student is UnderGraduate or PostGraduate.
Secondly, you should extend the child classes from Student class.
I hope the below code be helpful:
abstract class Student {
private String name;
private long id;
private String grade;
private int[] test;
private final int NUM_TESTS = 5;
public Student(){
name = "UN";
id = 0;
grade = "UN";
test = new int[NUM_TESTS];
}
public Student(String name, long id){
this.name = name;
this.id = id;
}
#Override
public String toString() {
//TODO: write your desire toString method
return getNUM_TESTS()+getName()+getId()+getGrade();
}
abstract void claculateResult();
public int getTestScore(int testNumber){
if(testNumber >= NUM_TESTS)
return 0;
return test[testNumber];
}
public void setTestScore(int testNumber, int score){
if(testNumber >= NUM_TESTS)
return;
test[testNumber] = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public int[] getTest() {
return test;
}
public void setTest(int[] test) {
this.test = test;
}
public int getNUM_TESTS() {
return NUM_TESTS;
}
}
and the UnderGraduate class would be:
public class UnderGraduate extends Student{
public UnderGraduate(){
}
public UnderGraduate(String name, long id){
super();
}
#Override
void claculateResult() {
//TODO: DO whatever you want
}
}
remember that the PostGraduate class is same as UnderGraduate.

Java object scope between methods

I'm having issues with this code running, I'm trying to get the program to print the strings below by using input from the other classes. As you can see, the info put into the new Bride and Location objects are being put in to a Wedding Object and then I need to try and retrieve the details from the wedding object and display it on screen like so:
Wedding data:
Bride: Amy Cronos, age: 29
Location: South Rd, suburb: Tonsley
but I am instead met with 4 identical errors relating to the place.getName, place.getSuburb() etc. etc. that say
Main.java:6: error: cannot find symbol
System.out.println("Location"+place.getStreet()+", suburb:
"+place.getsuburb());
symbol: variable place
location: class Main
I'm pretty sure this has something to do with the scope, but cant work out what I need to do.
What is causing this error and how do I fix it?
Here is the code:
public class WeddingDetails {
public static void main(String[] args) {
Bride person = new Bride("Amy Cronos", 29);
Location place = new Location("Tonsley", "South Rd");
Wedding wed = new Wedding(person, place);
show(wed);
}
public static void show(Wedding wed) {
System.out.println("Wedding data:");
System.out.println("Bride: " + person.getName() + ", age: " + person.getAge());
System.out.println("Location: " + place.getStreet() + ", suburb: " + place.getSuburb());
}
public static class Location {
private String suburb;
private String street;
Location(String suburb, String street) {
this.suburb = suburb;
this.street = street;
}
public String getSuburb() {
return suburb;
}
public String getStreet() {
return street;
}
}
public static class Bride {
private String name;
private int age;
Bride(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public static class Wedding {
private Bride person;
private Location place;
Wedding(Bride person, Location place) {
this.person = person;
this.place = place;
}
public Bride getBride() {
return person;
}
public Location getPlace() {
return place;
}
}
}
The issue here is your println statements are trying to access methods within objects, but by calling those methods on the wrong object. You should be accessing the Bride and Location objects with the Wedding class' getters (getBride() and getPlace(). The complete call would be wed.getBride().getName() and wed.getPlace().getStreet() so on.
Corrected code is below. NOTE: for the purposes of being able to compile all of the code inside one class, I added the static keyword to the Bride, Location and Wedding class declarations. You can just remove the static and copy and paste each class back into your .java files.
public class WeddingDetails {
public static void main(String[] args) {
Bride person = new Bride("Amy Cronos", 29);
Location place = new Location("Tonsley", "South Rd");
Wedding wed = new Wedding(person, place);
show(wed);
}
public static void show(Wedding wed) {
System.out.println("Wedding data:");
System.out.println("Bride: " + wed.getBride().getName() + ", age: " + wed.getBride().getAge());
System.out.println("Location: " + wed.getPlace().getStreet() + ", suburb: " + wed.getPlace().getSuburb());
}
public static class Location {
private String suburb;
private String street;
Location(String suburb, String street) {
this.suburb = suburb;
this.street = street;
}
public String getSuburb() {
return suburb;
}
public String getStreet() {
return street;
}
}
public static class Bride {
private String name;
private int age;
Bride(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public static class Wedding {
private Bride person;
private Location place;
Wedding(Bride person, Location place) {
this.person = person;
this.place = place;
}
public Bride getBride() {
return person;
}
public Location getPlace() {
return place;
}
}
}

Database access Java

I've got the following question. I got a little application which saves payments, dates and persons inside a database. Now I got the following POJO class:
public class Payment implements Serializable {
private int id;
private double payment;
private Date datum;
private String usage;
private String category;
private int importance;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPayment() {
return payment;
}
public void setPayment(double payment) {
this.payment = payment;
}
public Date getDatum() {
return datum;
}
public void setDatum(Date datum) {
this.datum = datum;
}
public String getUsage() {
return usage;
}
public void setUsage(String usage) {
this.usage = usage;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getImportance() {
return importance;
}
public void setImportance(int importance) {
this.importance = importance;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ID: ");
sb.append(id);
sb.append("\nPAYMENT: ");
sb.append(payment);
sb.append("\nDATE: ");
sb.append(datum);
sb.append("\nUSAGE: ");
sb.append(usage);
sb.append("\nCATEGORY: ");
sb.append(category);
sb.append("\nIMPORTANCE: ");
sb.append(importance);
return sb.toString();
}
}
So, I got also a class for my dates and persons. The question I've got is the following: Should I create for every Table in my database(in Java the Payment.class , Date.class and Person.class) a own transaction/access class which supports an .saveOrUpdate(), .list() or .delete() function?So maybe I got than a PaymentRansaction.class or an PersonTransaction.class.
Thanks for every help :)
It depends.
Do you have one table with transactions, then one model should be sufficient.
Create methods to create the transactions for you depending on Payment or Person.
BUT
If you have more then 1 table go for multiple classess, each table it's own class.

Song Class, Using abstract class and interface

What I'am trying to do with this program is output the information of a song using the toString on Song class. When I output it, everything is fine except the SongType/genre. It is still outputting UNDETERMINED.
abstract class Song implements ISong //SONG CLASS
{
private String name;
private String rating;
private int id;
private SongType genre;
public Song()
{
name = " ";
rating = " ";
id = 0;
genre = SongType.UNDETERMINED;
}
public Song(String name, String rating, int id)
{
this.name = name;
this.rating = rating;
this.id = id;
this.genre =Song.UNDETERMINED;
}
public void setName(String name)
{
this.name = name;
}
public void setRating(String rating)
{
this.rating = rating;
}
public void setID(int id)
{
this.id = id;
}
public String getName()
{
return(this.name);
}
public String getRating()
{
return(this.rating);
}
public int getID()
{
return(this.id);
}
#Override
public String toString()
{
return("Song: " + this.name +
"\nID: " + this.id +
"\nRating: " + this.rating +
"\nGenre: " + this.genre);
}
}
class Pop extends Song //POP CLASS
{
public Pop(String name, String rating, int id)
{
super(name, rating, id);
}
}
interface ISong //INTERFACE
{
public enum SongType {POP, COUNTRY, HIPHOP, SOUL, UNDETERMINED;}
}
public class test{
public static void main(String [] args)
{
Song one = new Pop("Pop Song", "Five", 123);
System.out.println(one);
}
}
When I output it, everything is fine except the SongType/genre. It is still outputting UNDETERMINED.
But where do you actually set your genre field to anything but SongType.UNDETERMINED?
I suggest that you give the Song class and ISong interface a public SongType getGenre() method that returns the current genre, as well as an appropriate setter method, public void setGenre(SongType genre) and constructors that accept a SongType genre parameter if need be. The toString() method should call the getGenre() method to get the current genre state.
Most important, you will need to set the genre in a concrete class to something other than SongType.UNDETERMINED before trying to print it out.

Categories

Resources