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];
}
Related
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.
I know there are a lot of pages about this question, but I cannot understand it in my case.
I need to print the array of objects. For example, I have an array of objects that hold objects from the "shape" class. Do I call the toString method for each object in the array, or do I code the toString method in ObjectList to print out the instance variables? If so, how do I do that?
public class Shape{
private String shapeName;
private int numSides;
public String toString(){
return shapeName + " has " + numSides + " sides.";
}
}
public class ObjectList{
private Object[] list = new Object[10];
private int numElement = 0;
public void add(Object next){
list[numElement] = next;
}
public String toString(){
// prints out the array of objects
// do I call the toString() method from the object?
// or do I print the instance variables? What am I printing?
// I'm guessing I do a for loop here
}
}
public class Driver{
public static void main(String[] args){
ObjectList list = new ObjectList();
Shape square = new Shape("square", 4);
Shape hex = new Shape("hexagon", 6);
list.add(square);
list.toString(); // prints out array of objects
}
I am aiming for it to print this:
square has 4 sides
hexagon has 6 sides
The simplest way to do this is use Arrays.toString:
Arrays.toString(myArray);
This will internally call the toString method of every element of your array.
So just override toString method in your Shape class and it should work fine.
To add further, override toString method in your class where you call Arrays.toString on your variable list :
public class ObjectList{
private Object[] list = new Object[10];
.............
public String toString(){
return Arrays.toString(list);
}
}
You can do this with bellowed code, make for loop in toString method to print each shape object.
class Shape{
private String shapeName;
private int numSides;
Shape(String shapeName, int numSides){
this.shapeName = shapeName;
this.numSides = numSides;
}
public String toString(){
return shapeName + " has " + numSides + " sides.";
}
}
class ObjectList{
private Object[] list = new Object[10];
private int numElement = 0;
public void add(Object next){
list[numElement] = next;
numElement++;
}
#Override
public String toString(){
String str="";
int i=0;
while(list[i] != null){
str += list[i]+"\n";
i++;
}
return str;
}
}
public class Driver{
public static void main(String[] args){
ObjectList list = new ObjectList();
Shape square = new Shape("square", 4);
Shape hex = new Shape("hexagon", 6);
list.add(hex);
list.add(square);
System.out.println(list);
}
}
Write a for-each statement in toString() of Object List and create a large String with '\n' characters and return it as a String . Or may be name displayListElement() will be semantically more correct in which you can simple print all the Objects in the list .
Indeed, you should call toString method for each of objects that you want to print and join them together. You can use StringBuilder to hold the string-in-the-making as follows:
public String toString() {
StringBuilder result = new StringBuilder();
for (int i = 0; i <= numElements; i++) {
result.append(list.toString() + "\n");
}
return result.toString();
}
Note that you need to increase numElements (e.g. numElements++) for each add operation as what pbabcdefp said in the comments. Also, you can use ArrayList class to manage "growing arrays".
I am making a program for airplane seating arrangements for a class and i ended up making two toString methods but when I run the program the toString method in my airplane class is making something not work specifically:
str= str + seats[i][j].toString();
I believe that simply deleting the toString method in the seat class and somehow putting it back into the airplane class toString method would fix the problem or make it simpler. What's wrong?
Airplane class:
public class Airplane
{
private Seat [ ] [ ] seats;
public static final int FIRST_CLASS = 1;
public static final int ECONOMY = 2;
private static final int FC_ROWS = 5;
private static final int FC_COLS = 4;
private static final int ECONOMY_ROWS = 5;
private static final int ECONOMY_COLS = 6;
public Airplane()
{
seats = new Seat[FC_ROWS][ECONOMY_COLS];
}
public String toString()
{
String str = "";
for (int i=0; i<FC_ROWS; i++) {
for (int j=0; j<ECONOMY_COLS; j++)
{
str= str + seats[i][j].toString();
}
str = str + "\n";
}
return str;
}
}
Seat Class:
public class Seat
{
private int seatType;
private boolean isReserved;
public static final int WINDOW = 1;
public static final int AISLE = 2;
public static final int CENTER = 3;
public Seat(int inSeatType)
{
seatType = inSeatType;
isReserved = false;
}
public int getSeatType()
{
return seatType;
}
public void reserveSeat()
{
isReserved = true;
}
public boolean isAvailable()
{
if (!isReserved)
{
return true;
}
else return false;
}
public String toString()
{
if(isReserved == false)
{
return "*";
}
else return "";
}
}
In Seat.toString you should print a " " not "".
You're array is FC_ROWS by ECONOMY_COLS, so you're not creating all the seats. You should probably have two arrays (one for FC, one for Economy), since FC_ROWS != ECONOMY_ROWS.
You aren't actually creating Seats in your constructor. Use a nested loop to create them, otherwise you will get a NullPointerException. Creating an array doesn't create the objects contained in the array.
When you're creating the seats in the Airplane constructor, use if statements to figure out if the seat is supposed to be a Window, Aisle, etc.
seats seems to does not have Seat's instance.
Add this code :
for (int i=0; i<FC_ROWS; i++) {
for (int j=0; j<ECONOMY_COLS; j++)
{
seats[i][j] = new Seat();
}
}
below this :
seats = new Seat[FC_ROWS][ECONOMY_COLS];
I think that in Seat::toString, you mean to return " " (a space) if it isn't reserved.
I am new to using arrays of objects but can't figure out what I am doing wrong and why I keep getting a Null pointer exception. I am trying to create an Theatre class with an array of spotlight objects that are either set to on or off. But - whenever I call on this array I get a null pointer exception.
package theatreLights;
public class TheatreSpotlightApp {
public static void main(String[] args) {
Theatre theTheatre = new Theatre(8);
System.out.println("element 5 " + theTheatre.arrayOfSpotlights[5].toString());
}
}
package theatreLights;
public class Theatre {
spotlight[] arrayOfSpotlights;
public Theatre(int N){
arrayOfSpotlights = new spotlight[N];
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i].turnOn();
}
}
}
package theatreLights;
public class spotlight {
int state;
public spotlight(){
state = 0;
}
public void turnOn(){
state = 1;
}
void turnOff(){
state = 0;
}
public String toString(){
String stringState = "";
if(state == 0){
stringState = "is off";
}
else if(state==1){
stringState = "is on";
}
return stringState;
}
}
I must be doing something basic wrong in creating the array but can't figure it out.
replace
arrayOfSpotlights[i].turnOn();
with
arrayOfSpotLights[i] = new Spotlight();
arrayOfSpotlights[i].turnOn();
The line
arrayOfSpotlights = new spotlight[N];
will create an array of spotlights. It will however not populate this array with spotlights.
When you do "arrayOfSpotlights = new spotlight[N];" you init an array of length N, what you need to do is also init each object in it:
for i=0; i<N; i++
arrayOfSpotlights[i] = new spotlight();
arrayOfSpotlights[i].turnOn();
Hope I'm correct :)
You are not creating an spotlight objects.
arrayOfSpotlights = new spotlight[N];
This just creates an array of references to spotlights, not the objects which are referenced.
The simple solution is
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i] = new spotlight();
arrayOfSpotlights[i].turnOn();
}
BTW You should use TitleCase for class names.
You could write your class like this, without using cryptic code like 0 and 1
public class Spotlight {
private String state;
public Spotlight() {
turnOff();
}
public void turnOn() {
state = "on";
}
void turnOff() {
state = "off";
}
public String toString() {
return "is " + state;
}
}
You declared the array arrayOfSpotlights, but didn't initialize the members of the array (so they are null - and you get the exception).
Change it to:
public class Theatre {
spotlight[] arrayOfSpotlights;
public Theatre(int N){
arrayOfSpotlights = new spotlight[N];
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i]=new spotlight();
arrayOfSpotlights[i].turnOn();
}
}
}
and it should work.
I cant get how to use/create oop code without word static. I read Sun tutorials, have book and examples. I know there are constructors, then "pointer" this etc. I can create some easy non-static methods with return statement. The real problem is, I just don't understand how it works.I hope some communication gives me kick to move on. If someone asks, this is not homework. I just want to learn how to code.
The following code are static methods and some very basic algorithms. I'd like to know how to change it to non-static code with logical steps(please.)
The second code shows some non-static code I can write but not fully understand nor use it as template to rewrite the first code.
Thanks in advance for any hints.
import java.util.Scanner;
/**
*
* #author
*/
public class NumberArray2{
public static int[] table() {
Scanner Scan = new Scanner(System.in);
System.out.println("How many numbers?");
int s = Scan.nextInt();
int[] tab = new int[s];
System.out.println("Write a numbers: ");
for(int i=0; i<tab.length; i++){
tab[i] = Scan.nextInt();
}
System.out.println("");
return tab;
}
static public void output(int [] tab){
for(int i=0; i<tab.length; i++){
if(tab[i] != 0)
System.out.println(tab[i]);
}
}
static public void max(int [] tab){
int maxNum = 0;
for(int i=0; i<tab.length; i++){
if(tab[i] > maxNum)
maxNum = tab[i];
}
//return maxNum;
System.out.println(maxNum);
}
static public void divide(int [] tab){
for(int i=0; i<tab.length; i++){
if((tab[i] % 3 == 0) && tab[i] != 0)
System.out.println(tab[i]);
}
}
static public void average(int [] tab){
int sum = 0;
for(int i=0; i<tab.length; i++)
sum = sum + tab[i];
int avervalue = sum/tab.length;
System.out.println(avervalue);
}
public static void isPrime(int[] tab) {
for (int i = 0; i < tab.length; i++) {
if (isPrimeNum(tab[i])) {
System.out.println(tab[i]);
}
}
}
public static boolean isPrimeNum(int n) {
boolean prime = true;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
if ((n % 2 != 0 && prime && n > 2) || n == 2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
int[] inputTable = table();
//int s = table();
System.out.println("Written numbers:");
output(inputTable);
System.out.println("Largest number: ");
max(inputTable);
System.out.println("All numbers that can be divided by three: ");
divide(inputTable);
System.out.println("Average value: ");
average(inputTable);
System.out.println("Prime numbers: ");
isPrime(inputTable);
}
}
Second code
public class Complex {
// datové složky
public double re;
public double im;
// konstruktory
public Complex() {
}
public Complex(double r) {
this(r, 0.0);
}
public Complex(double r, double i) {
re = r;
im = i;
}
public double abs() {
return Math.sqrt(re * re + im * im);
}
public Complex plus(Complex c) {
return new Complex(re + c.re, im + c.im);
}
public Complex minus(Complex c) {
return new Complex(re - c.re, im - c.im);
}
public String toString() {
return "[" + re + ", " + im + "]";
}
}
Let's start with a simple example:
public class Main
{
public static void main(final String[] argv)
{
final Person personA;
final Person personB;
personA = new Person("John", "Doe");
personB = new Person("Jane", "Doe");
System.out.println(personA.getFullName());
System.out.println(personB.getFullName());
}
}
class Person
{
private final String firstName;
private final String lastName;
public Person(final String fName,
final String lName)
{
firstName = fName;
lastName = lName;
}
public String getFullName()
{
return (lastName + ", " + firstName);
}
}
I am going to make a minor change to the getFullName method now:
public String getFullName()
{
return (this.lastName + ", " + this.firstName);
}
Notice the "this." that I now use.
The question is where did "this" come from? It is not declared as a variable anywhere - so it is like magic. It turns out that "this" is a hidden parameter to each instance method (an instance method is a method that is not static). You can essentially think that the compiler takes your code and re-writes it like this (in reality this is not what happens - but I wanted the code to compile):
public class Main
{
public static void main(final String[] argv)
{
final Person personA;
final Person personB;
personA = new Person("John", "Doe");
personB = new Person("Jane", "Doe");
System.out.println(Person.getFullName(personA));
System.out.println(Person.getFullName(personB));
}
}
class Person
{
private final String firstName;
private final String lastName;
public Person(final String fName,
final String lName)
{
firstName = fName;
lastName = lName;
}
public static String getFullName(final Person thisx)
{
return (thisx.lastName + ", " + thisx.firstName);
}
}
So when you are looking at the code remember that instance methods have a hidden parameter that tells it which actual object the variables belong to.
Hopefully this gets you going in the right direction, if so have a stab at re-writing the first class using objects - if you get stuck post what you tried, if you get all the way done post it and I am sure we help you see if you got it right.
First, OOP is based around objects. They should represent (abstract) real-world objects/concepts. The common example being:
Car
properties - engine, gearbox, chasis
methods - ignite, run, brake
The ignite method depends on the engine field.
Static methods are those that do not depend on object state. I.e. they are not associated with the notion of objects. Single-program algorithms, mathematical calculations, and such are preferably static. Why? Because they take an input and produce output, without the need to represent anything in the process, as objects. Furthermore, this saves unnecessary object instantiations.
Take a look at java.lang.Math - it's methods are static for that precise reason.
The program below has been coded by making the methods non-static.
import java.util.Scanner;
public class NumberArray2{
private int tab[]; // Now table becomes an instance variable.
// allocation and initilization of the table now happens in the constructor.
public NumberArray2() {
Scanner Scan = new Scanner(System.in);
System.out.println("How many numbers?");
int s = Scan.nextInt();
tab = new int[s];
System.out.println("Write a numbers: ");
for(int i=0; i<tab.length; i++){
tab[i] = Scan.nextInt();
}
System.out.println("");
}
public void output(){
for(int i=0; i<tab.length; i++){
if(tab[i] != 0)
System.out.println(tab[i]);
}
}
public void max(){
int maxNum = 0;
for(int i=0; i<tab.length; i++){
if(tab[i] > maxNum)
maxNum = tab[i];
}
System.out.println(maxNum);
}
public void divide(){
for(int i=0; i<tab.length; i++){
if((tab[i] % 3 == 0) && tab[i] != 0)
System.out.println(tab[i]);
}
}
public void average(){
int sum = 0;
for(int i=0; i<tab.length; i++)
sum = sum + tab[i];
int avervalue = sum/tab.length;
System.out.println(avervalue);
}
public void isPrime() {
for (int i = 0; i < tab.length; i++) {
if (isPrimeNum(tab[i])) {
System.out.println(tab[i]);
}
}
}
public boolean isPrimeNum(int n) {
boolean prime = true;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) {
prime = false;
break;
}
}
if ((n % 2 != 0 && prime && n > 2) || n == 2) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
// instatiate the class.
NumberArray2 obj = new NumberArray2();
System.out.println("Written numbers:");
obj.output(); // call the methods on the object..no need to pass table anymore.
System.out.println("Largest number: ");
obj.max();
System.out.println("All numbers that can be divided by three: ");
obj.divide();
System.out.println("Average value: ");
obj.average();
System.out.println("Prime numbers: ");
obj.isPrime();
}
}
Changes made:
int tab[] has now been made an
instance variable.
allocation and initialization of the
table happens in the constructor.
Since this must happen for every
instantiated object, it is better to
keep this in a constructor.
The methods need not be called with
table as an argument as all methods
have full access to the instance
variable(table in this case)
The methods have now been made
non-static, so they cannot be called
using the class name, instead we need
to instantiate the class to create an
object and then call the methods on
that object using the obj.method()
syntax.
It is easy to transform class methods from beeing static to non-static. All you have to do is remove "static" from all method names. (Ofc dont do it in public static void main as you would be unable to run the example)
Example:
public static boolean isPrimeNum(int n) { would become
public boolean isPrimeNum(int n) {
In public static void main where you call the methods you would have to chang your calls from beeing static, to refere to an object of the specified class.
Before:
NumberArray2.isPrimeNum(11);
After:
NumberArray2 numberarray2 = new NumberArray2(); // Create object of given class
numberarray2.isPrimeNum(11); // Call a method of the given object
In NumberArray2 you havent included an constructor (the constructor is like a contractor. He takes the blueprint (class file, NumberArray2) and follows the guidelines to make for example a building (object).
When you deside to not include a constructor the java compilator will add on for you. It would look like this:
public NumberArray2(){};
Hope this helps. And you are right, this looks like homework :D
I belive its common practice to supply the public modifier first. You haven done this in "your" first method, but in the others you have static public. Atleast for readability you should do both (code will compile ether way, as the compilator dosnt care).
The code is clean and easy to read. This is hard to do for someone who is "just want to learn how to code". Hope this helps you on your way with your "justlookslikehomeworkbutisnt" learning.
I'm guessing you're confused of what "static" does. In OOP everything is an object. Every object has its own functions/variables. e.g.
Person john = new Person("John",18);
Person alice = new Person("Alice",17);
if the function to set the 'name' variable would be non static i.e. string setName(string name){} this means that the object john has a name "John" and the object alice has a name "Alice"
static is used when you want to retain a value of something across all objects of the same class.
class Person{
static int amountOfPeopleCreated;
public Person(string name, int age){
amountOfPeopleCreated++;
setName(name);
setAge(age);
}
...
}
so if you'd the value of amountOfPeopleCreated will be the same no matter if you check alice or john.