accessing objects in an array Java - java

I am having trouble understanding how to set and get objects in an array. Please keep it basic/simple; I am a beginner.
I cannot use a list as I am not there yet in my java class. We are supposed to use regular arrays.
I am building a program that creates solar system objects and puts planet objects in the solar system object array. I have to be able to insert the planet by index as well as get it by index.
Getting regular object info was simple but once arrays were added. It got tough. I understand better when I can comprehend how and why something works. Here is my code. Many thanks in advance!
Planet Class
public class Planet {
// private fields
private String planetName;
private int numMoons;
// param constructor
public Planet(String n, int m){
planetName = n;
numMoons = m;
}
public String toString(){
return planetName + " " + numMoons;
}
public void setPlanetName(String n){
this.planetName = n;
}
public String getPlanetName(){
return planetName;
}
public void setNumMoons(int m){
this.numMoons = m;
}
public int getNumMoons(){
return numMoons;
}
}
Here is the SolarSystem class
package project03;
public class SolarSystem {
private String solarSystemName;
private Planet[] allPlanets = new Planet[8];
private int numPlanets;
public SolarSystem(String ss, int np){
solarSystemName = ss;
numPlanets = np;
}
public void setSolarSystemName(String ss){
solarSystemName = ss;
}
public String getSolarSystemName(){
return solarSystemName;
}
/*public void setAllPlanets(String ss){
solarSystemName = ss;
}
public String getSolarSystemName(){
return solarSystemName;
}
*/
}
Finally here is my driver class that houses the main method
package project03;
public class Driver {
public static void main(String[] args) {
// creates planet object
Planet Mercury = new Planet("Mercury", 0);
Planet Venus = new Planet("Venus", 0);
Planet Earth = new Planet("Earth", 1);
Planet Mars = new Planet("Mars", 2);
Planet Jupiter = new Planet("Jupiter", 67);
Planet Saturn = new Planet("Saturn", 62);
Planet Uranus = new Planet("Uranus", 27);
Planet Neptune = new Planet("Neptune", 14);
SolarSystem ourSolarSystem = new SolarSystem("Sol-System", 8);
System.out.println("Planet name is : " + ourSolarSystem.getSolarSystemName());
//System.out.println("Moon number is :" + Mercury.getNumMoons());
}
}

You are missing a couple of methods from your SolarSystem class
public void setPlanet (Planet planet, int pos) {
allPlanets [pos] = planet; // pos is zero based
}
public Planet getPlanet (int pos) {
return allPlanets [pos]; // pos is zero based
}
Then you can use it as
ourSolarSystem.setPlanet (Mercury, 0);

You have to add methods in your solar system class to add objects to the internal array.
to populate an array , you need 2 things
1. Size
2. Elements.
Your solar system class has provisions for none at this point. Size is hardcoded to 8, which is fine for this example, ideally it should be passed in constructor while creating a solar system.
Ignoring that for a moment, you should add method in the class to add a planet.
Since this is for your learning, I am not adding exact code, just algorithm
public void addPlanet(Planet p, int pos){
//check pos is less than array size
// add planet to the index pos if pos is less than size.
}
You could also create an array outside and add it to the solar planet
public void addPlanets(Planet[] planetArray){
// replace current planet array with the array passed in input
}
The array outside can be created easily
Planet[] planetArray = new Planet[8];
planetArray[0] = Mercury ;
// and so on.

Related

About having various constructors and parameters for java

I have written the instructions below and till now, I've came up with having two parameters and letting the method to assign the value and retrieving it. However, one of the instruction I had to follow was to include one constructor with no parameters, so I'm wondering what statement should I make inside the constructor without any parameters. It would be wonderful if anyone gives be a instruction. This is the code I've came up so far.
public class Rectangle {
//first constructor no parameters
//public<class name> (<parameters>)<statements>}
//two parameters one for length, one for width
//member variables store the length and the width
//member methods assign and retrieve the length and width
//returning the area and perimeter
static int recPerimeter(int l, int w) {
return 2*(l+w);
}
static int recArea(int l, int w) {
return l*w;
}
public static void main(String[] args) {
int p = recPerimeter(5, 3);
System.out.println("Perimeter of the rectangle : " + p);
int a = recArea(5,3);
System.out.println("Area of the rectangle : " + a);
}
}
First off, I would take some time to read the java tutorials. At least the "Covering the Basics"
There is a ton wrong with your example. You should store the the attributes of a rectangle - width and length as data members of the class which will get initialized with values through the constructors. If a default constructor is called with no values, then set the attributes to whatever you want. I set them to zero in the example.
Also, you need to normally create an instance of your class and then access it. Big red flag if you are having to prepend "static" to everything.
public class Rectangle {
private int recLength;
private int recWidth;
public Rectangle() {
recLength = 0;
recWidth = 0;
}
public Rectangle( int l, int w ) {
recLength = l;
recWidth = w;
}
public int calcPerimeter() {
return 2*(recLength+recWidth);
}
public int calcArea() {
return recLength*recWidth;
}
public static void main (String [] args) {
Rectangle rec = new Rectangle(5,3);
System.out.println("Perimeter = "+ rec.calcPerimeter());
System.out.println("area = " + rec.calcArea());
}
}

Car Search java

In one of my classes we created a program that randomly creates 10 cars with the price and star rating. Right now the program creates the 10 objects and then creates another object that it compare the 10 to. It searches by the star rating, sorts the 10 by star rating, then runs a binary search on the 10 objects. I have been trying to improve on it by adding in the car manufacturer name to each object but keep messing up the program. The program has two classes
import java.util.*;
import java.util.Scanner;
public class Sorter{
static Car [] ary; // declare
final static int NUM_CARS = 10;
public static void main() {
//Scanner rating = new Scanner(System.in);
//int r = rating.nextInt();
Car key = new Car();
ary = new Car[NUM_CARS]; // initialize
int i;
int position;
for (i=0; i<NUM_CARS; i++) {
ary [ i ] = new Car();
}
System.out.println("Unsorted:");
System.out.println(Arrays.toString(ary));
System.out.println("Sequential search for " + key);
ary[0].reset();
position = sequentialSearch(key)+1; //add one to the index position to display the position on screen that the user's desired search is first found
System.out.println("Total comparisons: "
+ ary[0].getAllCount());
System.out.println("Found a position: " +position);
System.out.println();
System.out.println("Sorted:");
ary[0].reset();
Arrays.sort(ary);
System.out.println("Total comparisons: "
+ ary[0].getAllCount());
System.out.println(Arrays.toString(ary));
System.out.println("Binary search for " + key);
ary[0].reset();
position = binarySearch(key)+1; //add one to the index position to display the position on screen that the user's desired search is first found
System.out.println("Found a position: " +position);
System.out.println("Total comparisons: "
+ ary[0].getAllCount());
}
public static int binarySearch (Car keyCar) {
return Arrays.binarySearch(ary,keyCar);
}
public static int sequentialSearch (Car keyCar) {
int pos = -1;
int i;
int answer;
for (i=0; i<ary.length; i++) {
answer = ary[i].compareTo(keyCar);
if (answer==0) {
pos = i;
break;
}
}
return pos;
}
}
Second class
import java.util.*;
/**
* in class work
*/
public class Car implements Comparable<Car> {
// instance variables - replace the example below with your own
int stars;
double price;
String name [] = {"Ford", "Dodge", "Chevrolet", "Honda", "Toyota", "VW", "Hyundai"};
int myCounter;
static int allCounter;
/**
* Constructor for objects of class Sorter
*/
public Car() {
Random generator = new Random ();
price = generator.nextDouble()*50000 + 50000;
stars = generator.nextInt(5)+1;
reset();
}
public String toString()
{
return String.format("$%,7.0f(%d stars)",price,stars);
//$ put dollar sign infront
//up to 7 digits
//, puts commas
}
/**
* Resets counter to zero
*/
public void reset(){
myCounter=0;
allCounter=0;
}
public int getMyCount() {
return myCounter;
}
public int getAllCount() {
return allCounter;
}
/**
* #param other A house to compare to.
* #return Returns 0 if they are equal
*/
public int compareTo(Car other)
{
myCounter++;
allCounter++;
if (this.stars < other.stars) {
return -1;
} else if (this.stars> other.stars) {
return +1;
}
return 0; // equals
}
}
How do I make it so that the objects will display the price, star rating, and the manufacturer?
Also, another thing I'd like to do but haven't tried yet is making it so the user can input what star rating they want and it'll display those cars only. This part is the next thing I'd like to try when time comes around to do so.
To associate data with an object, a variable to store that data needs to be in the object's constructor. So, to associate a manufacturer with each car object, you'll have to add String manufacturer or something similar as a variable in your Car class's constructor. It seems like you would then want to set that manufacturer variable to a random element of your String name [] array.
To make the car "display" the manufacturer variable you just created, you would have to modify the toString() method in your car class to print manufacturer as well as price and stars.

Online grading says my output values are not correct but I don't see why?

I am doing some homework for my java programming class, but this code is giving me trouble. The online program that grades it says there is a problem with my output, but I really don't see why. Can anyone help?
The assignment:
Write a class named Car that has the following fields:
yearModel: The yearModel field is an int that holds the car's year model.
make: The make field is a String object that holds the make of the car.
speed: The speed field is an int that holds the car's current speed.
In addition, the class should have the following methods :
Constructor : The constructor should accept the car's year model and make as arguments .
These values should be assigned to the object 's yearModel and make fields. The
constructor should also assign 0 to the speed field.
Accessor: The appropriate accessor methods should be implemented to access the values
stored in the object 's yearModel, make, and speed fields.
accelerate: The accelerate method should add 5 to the speed field when it is called.
brake: The brake method should subtract 5 from the speed field each time it is called.
Demonstrate the class in a program that contains a Car object , and then calls the
accelerate method five times. After each call to the accelerate method , get the current
speed of the car and print it on a separate line. Then, call the brake method five times,
each time printing the current speed of the car on a separate line.
My code:
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(int model, String m) {
yearModel = model;
make = m;
speed = 0;
}
public int getYearModel() {
return yearModel;
}
public String getMake() {
return make;
}
public int getSpeed() {
return speed;
}
public int accelerate() {
speed += 5;
return speed;
}
public int brake(int b) {
b -= 5;
return b;
}
}
class CarDemo {
public static void main(String[] args) {
Car c = new Car(1992, "Mustang");
int s = 0;
s = c.getSpeed();
for(int i = 0; i < 5; i++) {
System.out.println("The " + c.getYearModel() + " " + c.getMake() + "is going: " + s);
s = c.accelerate();
System.out.println("Now the " + c.getYearModel() + " " + c.getMake() + "is going: " + s);
}
}
}
Edit:
Based on the suggestions below, I have edited my code to the following; however, the system still says that my output is incorrect.
public class Car{
private int yearModel;
private String make;
private int speed;
public Car(int y, String m){
yearModel = y;
make = m;
speed = 0;
}
public int getYearModel(){
return yearModel;
}
public String getMake(){
return make;
}
public int getSpeed(){
return speed;
}
public void accelerate(){
speed += 5;
}
public void brake(){
speed -= 5;
}
}
class CarDemo{
public static void main(String[] args){
Car theCar = new Car(2010, "Porsch");
for(int i = 0; i < 5; i++){
theCar.accelerate();
System.out.println(theCar.getSpeed());
}
for(int count = 0; count < 5; count++){
theCar.brake();
System.out.println(theCar.getSpeed());
}
}
}
for brake you need to do speed -= 5, not b -= 5. Also I do not think the brake method needs an input argument.
In addition you accelerate 5 times but never brake
Your main issue is the brake method. The requirements state that it should subtract 5 from the current speed. So, you should make it like your accelerate method, but subtracting 5 instead of adding. It shouldn't take in a parameter.
Also, I don't know if this would cause an issue, but your accelerate and brake methods shouldn't return the speed, according to the requirements. Change their return types to void, and remove the return statements.
Lastly, You test main doesn't do exactly what the requirements say to do. Read it carefully to see what it should do, and do EXACTLY what it says.
Follow the specification.
The spec says:
accelerate: The accelerate method should add 5 to the speed field when it is called.
brake: The brake method should subtract 5 from the speed field each time it is called.
These 2 methods have no return type and take no arguments.
So, they should be:
public void accelerate() {
speed += 5;
}
// brake should not take an argument
public void brake() {
// this should be speed, not b
speed -= 5;
}
Additionally, your demo should follow the spec (in comments):
class CarDemo {
public static void main(String[] args) {
//Demonstrate the class in a program that contains a Car object
Car c = new Car(1992, "Mustang");
for (int i = 0; i < 5; i++) {
//and then calls the accelerate method five times.
c.accelerate();
//After each call to the accelerate method, get the current speed of the car and print it on a separate line.
System.out.println(c.getSpeed());
}
for (int i = 0; i < 5; i++) {
//Then, call the brake method five times,
c.brake();
//each time printing the current speed of the car on a separate line.
System.out.println(c.getSpeed());
}
}
}
When working off of a well-written, explicit specification as has been provided for your assignment, it can be very helpful to do what I've done above--include the spec as comments and fill in the code around them.
You're printing The " + c.getYearModel() + " " + c.getMake() + "is going: " + s 5 times. You should put that outside the loop so it's printed once only.
IMHO I don't think you need to be returning the speed from the accelerate() function either. I'd suggest making that a void function and using the getSpeed() method instead of assigning to an intermediate variable.
I am currently taking the Prog Fund I & II class. If you are using Pearson, then this should help. I had the answer correct the first time. You just have to format it correctly in the proper order as so.
import java.util.Scanner;
public class Car
{
private int yearModel; // Holds the car's year model
private String make; // Holds the make of the car
private int speed; // Holds the car's current speed
public static void main(String[] args)
{
// Creates car object
Car vehicle = new Car(2018, "Barbie Mobile");
// Creates object for user input
Scanner keyboard = new Scanner(System.in);
// Holds the speed of the car
int speed = 0;
// Calls accelerate 5 times
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
// Calls break 5 times
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
}
public Car(int year, String maker)
{
// Assigns values to car's year model and make
yearModel = year;
make = maker;
// Assigns 0 to the speed field
speed = 0;
}
/* #return gets year model */
public int getYearModel()
{
return yearModel;
}
/* #return The speed */
public int getSpeed()
{
return speed;
}
/* #return Gets the making of car */
public String getMake()
{
return make;
}
/* Adds 5 to speed when called */
public void accelerate()
{
speed += 5;
}
/* Subtracts 5 from speed when called */
public void brake()
{
speed -= 5;
}
}
I am taking the same class right now, using Pearson Revel. If anyone else comes across this problem, this should help.. Spoiler alert, I will be posting the answer to the problem below
Pearson Revel is such a pain in the butt, they do a horrible job describing how they want the programs structured and output displayed, and if anything is off by even one space or something similar, you lose all points. That being said, the problem demonstrates the calling of the program under "Sample Run" as java Car. So it sounds like the main program that creates a Car object and calls all of it's methods is within the same class (test it out in a text editor, you'll see that if you create a seperate class under the Car class and call Car.java from the command line, it will throw an error; stating the class Car does not have a main. So therefore, it's safe to say you need to create the main method inside of the Car class (wish they would just say that, right?).
Here is my graded & passing answer.
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(int year, String make) {
this.yearModel = year;
this.make = make;
this.speed = 0;
}
public void brake() {
this.speed -= 5;
}
public void accelerate() {
this.speed += 5;
}
public int getSpeed() {
return this.speed;
}
public String getMake() {
return this.make;
}
public int getYearModel() {
return this.yearModel;
}
public static void main(String[] args) {
Car myCar = new Car(2019, "Tacoma");
for (int i=0;i < 5;i++) {
myCar.accelerate();
System.out.println(myCar.getSpeed());
}
for (int i=0;i < 5;i++) {
myCar.brake();
System.out.println(myCar.getSpeed());
}
}
}
And here is Revel's suggested answer after completion
public class Car {
public static void main(String[] args) {
Car batmobile = new Car(1965, "Bat Mobile");
for(int i=0; i<5; i++){
batmobile.accelerate();
System.out.println(batmobile.getSpeed());
}
for(int i=0; i<5; i++){
batmobile.brake();
System.out.println(batmobile.getSpeed());
}
}
private int yearModel;
private String make;
private int speed;
public Car(int yearModel, String make){
this.yearModel = yearModel;
this.make = make;
this.speed = 0;
}
public int getYearModel(){
return this.yearModel;
}
public String getMake(){
return this.make;
}
public int getSpeed(){
return this.speed;
}
public void accelerate(){
this.speed += 5;
}
public void brake(){
this.speed -= 5;
}
}

storing command line args in an array class

Musical Chairs. Musical Chairs is a children’s game where the players walk around a group of chairs while some music is playing. When the music stops, everyone must sit down. But, there is one less chair than there are people, so someone gets left out. And, indeed, that person is out of the game. A chair is removed. And the game is played again; someone else goes out. This continues until there is only one player left, the winner.
I am having problems storing the command line arguments in the player[]
here is my code
import java.util.*;
public class MusicalChairs {
Player [] players;
Random r = new Random();
public static void main(String[] args){
MusicalChairs mc = new MusicalChairs();
mc.setUpGame(args);
}
public void setUpGame(String [] p){
System.out.println("This is how we stand.......");
for (int i = 0; i < p.length; i++){
System.out.println(p[i]+" is "+ Player.Status.IN);
}
}
public void showStatus(){
}
public void winner(){
System.out.println("is the winner");
}
}
class Player{
enum Status{IN,OUT};
private String name;
private Status status;
public Player(String n){
name=n;
}
public String getName(){
return name;
}
public void setStatus(Status s){
status=s;
}
public Status getStatus(){
return status;
}
public String toString(){
String ret = name;
if(status==Status.IN){
ret="IN ";
}
else{
ret="OUT ";
}
return ret;
}
}
You're not storing the arguments in your array. If your question is how to do it, then you should:
Initialize the players array.
For each argument, you must create a Player object and store it in the array.
Use the data in your program.
This could be done like this:
public void setUpGame(String [] p) {
System.out.println("This is how we stand.......");
//Initialize the `players` array.
players = new Player[p.length];
for (int i = 0; i < p.length; i++){
System.out.println(p[i]+" is "+ Player.Status.IN);
//For each argument, you must create a `Player` object and store it in the array.
players[i] = new Player(p[i]);
players[i].setStatus(Status.IN);
}
//Once your array is filled, use the data in your program.
//...
}
The question is still open: What's your specific problem?
I think you need to update your code to create new players and maintain the reference in your array...
public void setUpGame(String [] p){
System.out.println("This is how we stand.......");
// You may want to check for a 0 number of players...
players = new Player[p.length];
for (int i = 0; i < p.length; i++){
players[i] = new Player(p[i]);
players[i].setStatus(Player.Status.IN);
System.out.println(players[i].getName()+" is "+ players[i].getStatus());
}
}

Access object.variable in an array of objects

I need help with this piece of code.
public class ParkingLot {
static int MAX = 5;
static Car[] Slot = new Car[MAX];
public static void main(String[] args) {
Slot[0] = new Car("1234", "White");
Slot[1] = new Car("5678", "Black");
}
public static void Allot() {
for (int i = 0; i <= Slot.length; i++) {
System.out.println(Slot.getNo);
}
}
I am storing a Car Object in Slot. I wish to print/access the No and Colour of the car stored in slot. How do I go about doing that?
Well, if car has a public property, or a public getter method (this is preferable - getNumber() and getColour()), you can call them while iterating the array with the for-each loop:
for (Car car : slot) {
System.out.println(car.getColour());
}
Note that I've lowercased slot - variable names in Java should be lowercase. I'd also advise for naming the array with plural name - i.e. slots.
Note also that the way of iteration provided by others is possible, but not recommended for the basic case of iterating the whole array. Effective Java (Bloch) recommends using the foreach loop whenever possible.
Using [] notation:
public static void Allot() {
Car car;
for (int i = 0; i <= Slot.length; i++) {
// Get the car at this position in the array
car = Slot[i];
// Make sure it isn't null, since the array may not have
// a full set of cars
if (car != null) {
// Use the car reference
System.out.println(car.getNo());
}
}
}
(I assumed by the name that getNo was a method, not a property.)
E.g., Slot[0] gives you the first Car, from which you can access Car's properties and methods, so Slot[i] gives you the car at the ith position. (In the above I used a temporary variable to store the car, but you can use Slot[i].getNo() directly, it doesn't matter. I just didn't want to repeat the array lookup, even through HotSpot [the Sun JVM] will optimize it out even if I do.)
Sorry for being so late. I noticed something missing in the above answers, so here is the complete solution for the problem stated.
Here is the ParkingLot class with a call to Allot() method.
public class ParkingLot {
static int MAX = 5;
static Car[] Slot = new Car[MAX];
public static void main(String[] args) {
Slot[0] = new Car("1234", "White");
Slot[1] = new Car("5678", "Black");
Allot();
}
public static void Allot() {
for (int i = 0; i < Slot.length; i++) {
if (Slot[i] != null) {
System.out.println(Slot[i].getNo()+" , "+Slot[i].getColor());
}
}
}
}
And the Car class with the getNo() and getColor() methods.
public class Car {
private String Number;
private String Color;
Car (String Number, String Color){
this.Number = Number;
this.Color = Color;
}
public String getNo(){
return Number;
}
public String getColor(){
return Color;
}
}
class Car{
String number;
String color;
public Car(String number, String color) {
this.number = number;
this.color = color;
}
#Override
public String toString() {
return "Car{" +
"number='" + number + '\'' +
", color='" + color + '\'' +
'}';
}
}
class Test{
static int MAX = 5;
static Car[] Slot = new Car[MAX];
public static void main(String[] args) {
Slot[0] = new Car("1234", "White");
Slot[1] = new Car("5678", "Black");
for (Car car : Slot)
System.out.println(car);
}
}
you can create and access object array of objects simply like this
Object[] row={"xx","xcxcx"};
Object[] cotainer = {row,row,row};
for(int a=0;a<cotainer.length;a++){
Object[] obj = (Object[])cotainer[a];
}

Categories