Do i need to add objects dynamically in this case? - java

So i've been asked to create a simple solar system simulator for my coursework. Our lecturer has set out very specific guidelines in terms of the structure of constructors and methods of our classes.
I've been thinking about this for a couple of hours and don't understand how i can make this work without dynamic object allocation. I want to add planets onto the Planet[] array so they can be indexed, but i don't know how i should create the objects considering a requirement is that you can add planets to the system until the user types 'DONE'.
The Planet class is not one of the requirements but he recommended we use a class that can store the variables for a single planet and do calculations on it. Whereas the data should be stored in the main SolarSystem class. We also need to use a FantasySolarSystem class to read data from the user and deal with output.
import java.util.*;
public class SolarSystem{
public static final int PLANET_MAX = 10;
public static void main(String[] args){
String systemName;
Planet[] planetArray = new Planet[PLANET_MAX]; //const for array size seemed easier than dynamically allocating memory
SolarSystem mySystem = new SolarSystem("Boris");
// below is testing the addplanet function
addPlanet("Jimmy", 10, 100);
System.out.print(Planet[0].planetName);
}
public SolarSystem(String name){
systemName = name;
}
public static void addPlanet(String planetName, double planetMass, double planetDistance){
Planet newPlanet = new Planet(planetName, planetMass, planetDistance);
// all i want to do here is add planets on to the array
Planet[0] = newPlanet;
}
}
Just for reference here is the Planet class:
public class Planet{
private String planetName;
private double planetMass;
private double planetDistance;
private double planetPeriod;
public Planet(String planetName, double planetMass, double planetDistance){
this.planetName = planetName;
this.planetMass = planetMass;
this.planetDistance = planetDistance;
}
//sets the period for the current object
public static calculatePeriod(double planetDistance){
double period = Math.sqrt(planetDistance*planetDistance*planetDistance);
setPlanetPeriod(period);
}
//accessors
public String getPlanetName(){
return planetName;
}
public double getPlanetMass(){
return planetMass;
}
public double getPlanetDistance(){
return planetDistance;
}
public double getPlanetPeriod(){
return planetPeriod;
}
//mutators
public void setPlanetName(String planetName){
this.planetName = planetName;
}
public void setPlanetMass(double planetMass){
this.planetMass = planetMass;
}
public void setPlanetDistance(double planetDistance){
this.planetDistance = planetDistance;
}
public void setPlanetPeriod(double planetPeriod){
this.planetPeriod = planetPeriod;
}
}
Any assistance would be much appreciated.
edit: I would just write it and test it but im getting errors saying, cannot find symbol in places referring to the object array
edit2: Fixed the accessing non-static methods from static methods issue, but still having problems with adding objects to arrays (still have 3 more cannot find symbol errors, with systemName=name; and both times i use Planet[0])

Related

Getting Variables From Java constructor

I'm new to Java programming, sorry if this is a dumb question.
I find it hard to word this question properly, but I have an assignment to create a aircraft class that can make aircraft land, takeoff etc. And need to test it using Testclass. When the new object are entered it automatically assigns a unique ID to the aircraft in the constructor.
I can do this using a instance method fine as it has a return value which is returned to to Testclass. The question wants me to do this in the constructor itself, however, the constructor never returns anything. So the variable never gets sent to the Testclass. I clearly am not understanding OOP properly. Even when I try to just use a getter method to get the ID created in the constructor it gives me the initialized variable before the the constructor has worked on this. This is the code I have so far and its completely wrong I know but if someone could point me in the right direction or tell me how to word this question better it would be a massive help.
// I need to enter 3 aircraft into the system in the testclass
public class Aircraft {
private int aircraftID;
private static int lastID;
private String airportcode;
private int ID = 100;
private int count;
public Aircraft(int a, int b, int c){
// Constructor
// Assign ID
this.ID = a;
lastID = ID;
ID++;
this.ID =b;
lastID = ID;
ID++;
}
}
OK, you want to create an Aircraft that has an automatically-assigned unique identifier, and can take off and land. That implies you need a field for tracking the identifier, a field for tracking whether it's in the air (or not), and methods for the take off and land operations. You also need a static field for generating the unique identifiers. (Note that this implementation isn't thread safe.)
private class Aircraft {
private static int staticId = 0;
private int uniqueId = 0;
private boolean onGround = true; // Aircraft start on the ground in this implementation
public Aircraft(){
this.uniqueId = staticId; // putting this line first makes uniqueId zero-indexed in effect
staticId++;
}
public void land(){
onGround = true;
}
public void takeoff(){
onGround = false;
}
public boolean isFlying(){
return !onGround; // If it's not on the ground, it's flying
}
public int getUniqueId(){
return uniqueId;
}
}
Unit tests checks all of the methods and expected functionality of the class in question:
import org.junit.Test;
import static org.junit.Assert.*;
import Aircraft;
class Testclass {
private final Aircraft aircraft = new Aircraft();
#Test
public void hasId(){
aircraft.getUniqueId() >= 0;
}
#Test
public void canLand(){
assertTrue(aircraft.land());
}
#Test
public void canTakeOff(){
assertTrue(aircraft.takeOff());
}
#Test
public void checkFlightOperationsAreTrackedCorrectly(){
aircraft.land();
assertFalse(aircraft.isFlying());
aircraft.takeOff();
assertTrue(aircraft.isFlying());
}
}
As pointed out a constructor does not return anything (the simplified version is that with new it returns an object instance). I am kinda guessing at what you are trying to acomplish, but I'll have a go anyways. It seems to me that you are trying to cram the construction of 3 objects into one constructor - which is why your constructor has 3 parameters. Also you are playing havoc with the IDs.
I have removed all the variables that I didnt quite understand, leaving only ID that increments with each instantiated Aircraft. The #Override is mainly just for show.
public class Aircraft {
private int aircraftID;
private static int lastID = 0;
#Override
public String toString(){
return "Aircraft_" + this.aircraftID;
}
public Aircraft() {
lastID++;
this.aircraftID = lastID;
}
}
I took the liberty and wrote the TestClass just to see if we have the same thing in mind. Again the printAircraft() method is for show.
public class TestClass {
private List<Aircraft> aircrafts;
public TestClass(){
aircrafts = new ArrayList<>();
}
public void addAircraft(Aircraft a){
aircrafts.add(a);
}
public void printAircraft(){
Iterator<Aircraft> it = aircrafts.iterator();
while(it.hasNext()){
System.out.println(it.next().toString());
}
}
}
and to test it, we create and instance of TestClass add 3 Aircraft instances and print out the contents
public static void main(String[] args) {
TestClass tc = new TestClass();
tc.addAircraft(new Aircraft());
tc.addAircraft(new Aircraft());
tc.addAircraft(new Aircraft());
tc.printAircraft();
}
This would be the case if you are to write the TestClass. If that is given, it would help to know what it looks like - maybe that would help us understand better.

Method 'set(double)' is never used for my double variables but it is used for my string variable - in this arraylist class

I am trying to put together an arraylist and I made a separate class to establish the objects used. I am able to get my getMethod and setMethod for my string variable to work but I am unable to figure out my setMethod for my double variables to work. I am able to get my getMethod for my double variables. The variable names all appear to be correct so I am stuck as to what is missing. Any help will be appreciated.
Here is my code:
public class MessierData {
private String messierLocation;
private double messierRA;
private double messierDEC;
private double messierAZ;
private double messierALT;
public MessierData(String messierLocation,double messierRA, double messierDEC,
double messierAZ, double messierALT ) {
this.messierLocation = messierLocation;
this.messierRA = messierRA;
this.messierDEC = messierDEC;
this.messierAZ = messierAZ;
this.messierALT = messierALT;
}
#Override
public String toString() {
return messierLocation;
}
public String getMessierLocation (){
return messierLocation;
}
public void setMessierLocation(String messierLocation){
this.messierLocation = messierLocation;
}
public double getMessierRA(){
return messierRA;
}
public void setMessierRA( double messierRA){
this.messierRA = messierRA;
}
public double getMessierDEC(){return messierDEC;}
public void setMessierDEC(double messierDEC){
this.messierDEC = messierDEC;
}
public double getMessierAZ(){return messierAZ;}
public void setMessierAZ(double messierAZ){
this.messierAZ = messierAZ;
}
public double getMessierALT(){return messierALT;}
public void setMessierALT( double messierALT){
this.messierALT = messierALT;
}
}
Just a reminder. The setMethod for my string is working properly. The setMethod for my double variables however are not.
Here is my arraylist:
private List<MessierData> messierList() {
List<MessierData> messiervalues = new ArrayList<>();
messiervalues.add(new MessierData(Andromeda.getAndromedaHorizon(),Andromeda.getAndromedaRA()
,Andromeda.getAndromedaDec(), Andromeda.getAndromedaAZ(),Andromeda.getAndromedaALT()));
messiervalues.add(new MessierData(BeehiveCluster.getBeehiveHorizon(),BeehiveCluster.getBeehiveRA(),
BeehiveCluster.getBeehiveDec(),BeehiveCluster.getBeehiveAZ(),BeehiveCluster.getBeehiveALT()));
messiervalues.add(new MessierData(BlackEyeGalaxy.getBlackEyeHorizon(),BlackEyeGalaxy.getBlackEyeRA(),
BlackEyeGalaxy.getBlackEyeDec(),BlackEyeGalaxy.getBlackEyeAZ(),BlackEyeGalaxy.getBlackEyeALT()));
messiervalues.add(new MessierData(BodesGalaxy.getBodesHorizon(),BodesGalaxy.getBodesRA()
,BodesGalaxy.getBodesDec(),BodesGalaxy.getBodesAZ(),BodesGalaxy.getBodesALT()));
messiervalues.add(new MessierData(ButterflyCluster.getButterflyHorizon(),ButterflyCluster.getButterflyRA(),
ButterflyCluster.getButterflyDec(),ButterflyCluster.getButterflyAZ(),ButterflyCluster.getButterflyALT()));
messiervalues.add(new MessierData(CetusGalaxy.getCetusHorizon(),CetusGalaxy.getCetusRA(),
CetusGalaxy.getCetusDec(),CetusGalaxy.getCetusAZ(),CetusGalaxy.getCetusALT()));
return messiervalues;
}

Shallow Copy of Instance of Class within an ArrayList

I have an ArrayList which contains n instances of the class Boat. The class Boat has a number of methods which alter the instance variables of that boat.
For example:
public void Command(String command)
{
int inefficientwayofdoingthis=0;
if(command.equals("power on"))
{
inefficientwayofdoingthis++;
int x=1;
setpower(x);
System.out.println(name+" is on and is travelling in the direction of "+angle+" deg. with speed: "+ speed+"mph");
}
//...
The issue I am having is that this Command method should set the value of [instancename].power to 1.
The instances are contained in an ArrayList, data:
I am using the following code to alter the instances within the arraylist:
int numberinArray = whatever;
String theorder = "power on";
data.get(numberinArray).Command(theorder);
Each time I do so however, the command works and an output is produced, but subsequent commands do not seem to recognize that data.get(numberinArray).power should equal 1. I think I'm having a problem in that this is a deep copy of each instance of the class rather than a shallow copy. Would anyone have any suggestions on how to alleviate this issue?
if you want the power stay "attached" to the boat instance, this should be an instance variable. This could work in a way like this:
package com;
public class Boat {
private int power;
private String color;
Boat() {
// may want to initialize some values
this.setPower(0);
this.setColor("red");
}
public int getPower() {
return power;
}
public void setPower(int power) {
this.power = power;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
then you could add some other methods like applyCommand(String command) in your example

Having issues creating an application that instantiates an object of each type and displays the details

First I'm new and don't know if this is against the rules but I'm looking for a little help on my homework. I don't want a full answer, just a step in the right direction. The problem is as follows:
Mick’s Wicks makes candles in various sizes. Create a class for the business named Candle that contains data fields for color, height, and price. Create get methods for all three fields. Create set methods for color and height, but not for price. Instead, when height is set, determine the price as $2 per inch. Create a child class named ScentedCandle that contains an additional data field named scent and methods to get and set it. In the child class, override the parent’s setHeight() method to set the price of a ScentedCandle object at $3 per inch. Write an application that instantiates an object of each type and displays the details. Save the files as Candle.java, ScentedCandle.java, and DemoCandles.java.
Now I believe I have done the classes correctly but the issue I'm having is the "Write an application that instantiates an object of each type and displays the details." I just dont get it. Here's my code:
public class Candle {
public static int color; //Declaring Variables
public static int height;
public static int price;
Candle(int startColor, int startHeight, int startPrice) { //Constructor
color = startColor;
height = startHeight;
price = startPrice;
}
public static int getColor() //Public methods
{
return color;
}
public void setColor(int color)
{
Candle.color = color;
}
public static int getHeight()
{
return height;
}
public void setHeight(int height)
{
Candle.height = height;
}
public static int getPrice()
{
return price;
}
public void setPrice(int price)
{
Candle.price = 2 * height;
}
}
public class ScentedCandle extends Candle { //Creating subclass to superclass Candle
public static int scent; //Delcare Variable
public ScentedCandle(int startScent,int startColor, int startHeight,int startPrice) { //Constructor
super(startColor, startHeight, startPrice); //Calling from superclass Candle
scent = startScent;
}
public static int getScent() //Public methods
{
return scent;
}
public void setScent(int scent)
{
ScentedCandle.scent = scent;
}
public static int getPrice()
{
return price;
}
#Override
public void setPrice(int price)
{
Candle.price = 3 * height;
}
}
public class DemoCandles { //Here is where I'm lost and have no clue
public static void main(String[] args) {
Candle getColor; //Declaring Variables
Candle getHeight;
Candle getPrice;
ScentedCandle getScent;
getColor = new Candle();
getHeight = new Candle();
getPrice = new Candle();
getScent = new ScentedCandle();
}
}
First of all you need to declare price as a product of height and 2.
"Write an application that instantiates an object
of each type and displays the details."
This basically mean Create a class with a main method in order to run your program.
In that main method, you need to instantiate your Candle class.
Instantiate means to create an object instance of your Candle class.
Something like this:
Object object = new Object(someInt, someInt, someInt); // or which ever constructor you decide to you
In order to get the properties of the object, use your get methods. If the property(data field) does not have a get method, get the property with something like this Object.property
And do like RC said, read up on static. You're not using it right

Java Error: The constructor is undefined

In Java, Why am I getting this error:
Error: The constructor WeightIn() is undefined
Java Code:
public class WeightIn{
private double weight;
private double height;
public WeightIn (double weightIn, double heightIn){
weight = weightIn;
height = heightIn;
}
public void setWeight(double weightIn){
weight = weightIn;
}
public void setHeight(double heightIn){
height = heightIn;
}
}
public class WeightInApp{
public static void main (String [] args){
WeightIn weight1 = new WeightIn(); //Error happens here.
weight1.setWeight(3.65);
weight2.setHeight(1.7);
}
}
I have a constructor defined.
Add this to your class:
public WeightIn(){
}
Please understand that default no-argument constructor is provided only if no other constructor is written
If you write any constructor, then compiler does not provided default no-arg constructor. You have to specify one.
With your current implementation, you can't do WeightIn weight1 = new WeightIn(); since default constructor is not defined.
So you can add
public WeightIn(){
}
Or you can do this
WeightIn weight1 = new WeightIn(3.65,1.7) // constructor accept two double values
The compiler is encountering a call to a "WeightIn()" no argument constructor, on this line:
WeightIn weight1 = new WeightIn(); //Error happens here.
The compiler is looking for a matching constructor in the class definition, and its not finding it. That's the error. (You do have a constructor defined: "WeightIn(double,double)" but that takes two arguments, and is not match.)
Several ways to fix this.
The easiest is to change the code in your main method to pass two arguments.
WeightIn weight1 = new WeightIn( 3.65, 1.7);
//weight1.setWeight(3.65);
//weight2.setHeight(1.7);
The calls to the setWeight and setHeight methods are redundant, since the members are already assigned values by the constructor method.
You do not have the constructor WeightIn() .Create it or give parameters in main method to constructor.
WeightIn weight1 = new WeightIn();
The default constructor is not defined. Please define it like this:-
public weightIn()
{
}
In Java, Why am I getting this error:
Error: The constructor WeightIn() is undefined
It's simply because you didn't have the matching constructor for your class:
public class WeightIn {
...
public WeightIn (double weightIn, double heightIn){
weight = weightIn;
height = heightIn;
}
...
}
you need to add the public WeightIn() {}.
In Java, the default constructor is automatically generated by the compiler if you didn't defined it. So, when you define the following class:
public class WeightIn {
private double weight;
private double height;
// didn't define a constructor.
public void setWeight(double weightIn){
weight = weightIn;
}
public void setHeight(double heightIn){
height = heightIn;
}
}
compiler will generating a matching default constructor for you. So, your class is implicitly having a default constructor like this:
public class WeightIn {
private double weight;
private double height;
// automatically generated by compiler
public WeightIn() {
// do nothing here.
}
// didn't define a constructor.
public void setWeight(double weightIn){
weight = weightIn;
}
public void setHeight(double heightIn){
height = heightIn;
}
}
when you instantiate the class with:
WeightIn weight = new WeightIn();
everything is alright.
But when you're adding a constructor by yourself, the default constructor will not generated by the compiler. So, when you're creating the class with:
public class WeightIn {
...
// this won't automatically generated by compiler
// public WeightIn() {
// nothing to do here.
//}
public WeightIn (double weightIn, double heightIn){
weight = weightIn;
height = heightIn;
}
...
}
You won't have the default constructor (i.e public WeightIn(){}). And using the following will raise an error because you have no matching constructor:
WeightIn weight = new WeightIn();
First of all, you should know that one .java file can have only one public class.
You are getting error because you have written parameterised constructor and accessing a default constructor. To fix this error write:
WeightIn weight1 = new WeightIn(5.2, 52.2);
instead of
WeightIn weight1 = new WeightIn();
It took me a while but I think I finally figured out a way for this program to work.
I separated the classes into different files and renamed the weight Class to Record just so that it's more obvious instead of everything being named some variation of weight. I also added an Output class to keep the code in the main as clean and minimal as possible.
I hope this is similar to what you were hoping to do.
Original Code: "Constructor"
public class WeightIn{
private double weight;
private double height;
public WeightIn (double weightIn, double heightIn){
weight = weightIn; //needs to be : this.weight = weight
height = heightIn; //needs to be : this.height = height
}
Project: weightInApp
Package: weightInApp
Class: Record.Java
package weightInApp;
class Record
{
private double weight; //declare variables
private double height;
Record (double weight, double height) { //Parameterized Constructor method
this.weight = weight; //this is the correct way
this.height = height;
//if you want to use weightIn and/or heightIn you have to be consistent acrosss
//the whole class. I decided to drop "In" off the variables for brevity.
}
//Getters and setters
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
}
Project: weightInApp
Package: weightInApp
Class: Output.Java
This class outputs the set values to a table on the console. This can be manually altered to add more data. you could also consider tracking the date of the record and adding that to this output. you would need to add the requisite variables, getters, and setters in the Record Class for that functionality.
package weightInApp;
public class Output {
static void output (Record weightIn1, Record weightIn2)
{
int count = 0;
final Object[][] table = new Object[3][3];
table[0] = new Object[] { "Record", "Weight", "Height"};
table[1] = new Object[] { count +=1, weightIn1.getWeight(), weightIn1.getHeight() };
table[2] = new Object[] { count+=1, weightIn2.getWeight(), weightIn2.getHeight() };
for (final Object[] row : table) {
System.out.format("%15s%15s%15s\n", row);
}
}
}
Project: weightInApp
Package: weightInApp
Class: Main.Java
package weightInApp;
import weightInApp.Record; //imports methods and variables from the other classes
import weightInApp.Output;
public class Main {
public static void main (String [] args){
Record weightIn1 = new Record(0,0);
//previous line of code creates a new Record object named weightIn1
//previous line of code also sets both the values of weight and height to 0.
weightIn1.setWeight(3.65); //sets weight for weightIn1
weightIn1.setHeight(1.70);//sets Height for WeightIn1
Record weightIn2 = new Record(0, 0);
weightIn2.setWeight(3.00);
weightIn2.setHeight(1.75);
//previous 3 lines are the same as above for weightIn1
//except this is for a second object named weightIn2
Output.output(weightIn1, weightIn2); //calls runs passes values to output method
}
}
Sample Output
output sample from console

Categories