I'm pretty new in java and I'm doing a simple program but I don't know why I get different values, i.e., if I use getX, getY and getZ I get (6,5,8) but if I use toString I get different values for X and Y (3, 4, 8), so can anyone explain me why it happens because as far as I understand it should get the same values in both cases or what I'm doing wrong?
public class Coordinates {
private double coorX, coorY;
Coordinates()
{
coorX = 1;
coorY = 1;
}
Coordinates(double x, double y)
{
coorX = x;
coorY = y;
}
void setX(double x)
{
coorX = x;
}
void setY(double y)
{
coorY = y;
}
double getX()
{
return coorX;
}
double getY()
{
return coorY;
}
public String toString()
{
String myString = "(" + coorX + " , " + coorY + ")";
return myString;
}
public class Coordinates3D extends Coordinates{
private double coorZ;
Coordinates3D()
{
super();
coorZ = 1;
}
Coordinates3D(double x, double y, double z)
{
super(x,y);
coorZ = z;
}
public void setZ(double z)
{
coorZ = z;
}
double getZ()
{
return coorZ;
}
#Override
public String toString()
{
String myString = "(" + coorX + " , " + coorY + " , " + coorZ + ")" ;
return myString;
}
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Coordinates test1 = new Coordinates(3,4);
System.out.println(test1.toString());
System.out.println(test1.getX());
System.out.println(test1.getY());
Coordinates3D test2 = test1.new Coordinates3D(6,5,8);
System.out.println(test2.toString()); ---> here is the problem
System.out.println(test2.getX());
System.out.println(test2.getY());
System.out.println(test2.getZ());
}
}
First there is a problem on how you define the visibility of the fields of the super class:
public class Coordinates {
//defines as private
//sub classes cannot access to these fields directly
private double coorX, coorY;
This is that you cannot invoke super.coorX nor super.coorY on any sub class e.g. Coordinates3D. So, in toString method, when you have this code:
String myString = "(" + coorX + " , " + coorY + " , " + coorZ + ")" ;
It compiles and runs fine because Coordinates3D is an inner class. So, when using coorX here it's accessing to the value of coorX field stored in the instance of Coordinates class that created the instance of Coordinates3D. This can be easy to replicate if you separate the classes:
class Coordinates {
private double coorX, coorY;
}
public class Coordinates3D extends Coordinates {
//current code...
#Override
public String toString() {
//now you will get a compilaton error
String myString = "(" + coorX + " , " + coorY + " , " + coorZ + ")" ;
return myString;
}
}
The best solution would be:
mark the fields in the super class as protected
separate the classes
If you still want to keep Coordinates3D as inner class (not recommended), then:
mark the fields in the super class as protected
use super.coorX and super.coorY to not have the same unexpected behavior.
I would like to add to the existing answers that even in the class, you should not read the fields firectly, but use their getters.
#Override
public String toString() {
String myString = "(" + getX() + " , " + getY() + " , " + getZ() + ")";
return myString;
}
This also fixes the problem, but you should still not make the Coordinates3D class an inner class of Coordinates.
Related
when I go to print out the array, it prints the value for the last object called for. How can i get it to print out the different objects in the array? I think there is an error in the method I use to call upon the location of the object's variables stored in the array.
class Recorder4 {
int xPos, yPos;
String eventType;
final int EVENT_MAX = 10;
EventInformation[] event = new EventInformation [EVENT_MAX]; //this is the array
int xevent = 0;
Recorder4 (int xPos, int yPos, String eventType) {
this.xPos = xPos;
this.yPos = yPos;
this.eventType = eventType;
}
public void recordEvent (String Time, int Datum) {
if (xevent <= EVENT_MAX) {
event[xevent] = new EventInformation(Time, Datum);
xevent++; //this is where new instances of the object are assigned a place in the array
}
else {System.out.println("Event log overflow - terminating");
System.exit(1);}
}
void printEvents() {
System.out.println("Record of " + eventType +
" events at [" + xPos + ","+ yPos + "]");
for (int i = 0; i < xevent; i++) {
System.out.println("Event number " +
i + " was recorded at " + event[i].getTime() //i think these methods is where the issue lies
+ " with datum = " + event[i].getDatum());
}
}
}
class EventInformation {
static String eventTime;
static int eventDatum;
EventInformation (String s, int i) {
eventTime = s;
eventDatum = i;}
public int getDatum() {
return EventInformation.eventDatum;}
public String getTime() {
return EventInformation.eventTime;}
}
The problem might be in how you are defining your class variables. In your EventInformation class you are defining them as static:
static String eventTime;
static int eventDatum;
This means there will only be ONE copy of each of these variables no matter how many EventInformation instances you create (ie they will all share the same copy).
Try removing the static keyword from the variable declarations to see if that resolves your issue.
Can anyone please tell why the getSpeed method does not work ?
Whenever I hover over the method I get the :
to insert ;
illegal modifier
syntax error please insert []
syntax error on token
public class Tanks {
private String TankName;
private int TankModel;
private int CrewNumber;
private double Speed;
private int TurretSpeed;
Tanks (String name, int model, int crew, double speed, int turretspeed){
this.TankName = name;
this.TankModel = model;
this.CrewNumber = crew;
this.Speed = speed;
this.TurretSpeed = turretspeed;
}
public static void main(String[] args) {
Tanks merkava = new Tanks ("MERKAVA", 1, 5, 56.64, 67);
Tanks judge = new Tanks ("JUDGE", 2, 6, 66.66, 68);
public double getSpeed() {
return Speed;
}
System.out.println(merkava.TankName+ " "+merkava.TankModel+" "+merkava.CrewNumber+" "+merkava.Speed+" "+merkava.TurretSpeed);
System.out.println(judge.TankName+ " "+judge.TankModel+" "+judge.CrewNumber+" "+judge.Speed+" "+judge.TurretSpeed);
}
}
Your main method contains the following method.
public double getSpeed() {
return Speed;
}
Please move this to Tanks class.
Following should work:
public class Tanks {
private String TankName;
private int TankModel;
private int CrewNumber;
private double Speed;
private int TurretSpeed;
Tanks(String name, int model, int crew, double speed, int turretspeed) {
this.TankName = name;
this.TankModel = model;
this.CrewNumber = crew;
this.Speed = speed;
this.TurretSpeed = turretspeed;
}
public double getSpeed() {
return Speed;
}
public static void main(String[] args) {
Tanks merkava = new Tanks("MERKAVA", 1, 5, 56.64, 67);
Tanks judge = new Tanks("JUDGE", 2, 6, 66.66, 68);
System.out.println(merkava.TankName + " " + merkava.TankModel + " " + merkava.CrewNumber + " " + merkava.Speed
+ " " + merkava.TurretSpeed);
System.out.println(judge.TankName + " " + judge.TankModel + " " + judge.CrewNumber + " " + judge.Speed + " "
+ judge.TurretSpeed);
}
}
If you have gone through some basic Java course you will know that by defining a method (in this case getSpeed()) inside another function (main) is wrong.
I need to write a function to College department :
Add function adds additional lecturer.
Action returns false if there is no place to add additional lecturer, and at the same true if the lecturer was successfully added.
What I had written so far:
public boolean newLecturer(Lecturer[] AllLecturer) {
int MaxLecturer = 0;
MaxLecturer = this.maxLecturer;
int sum = 0;
sum += 1;
if (sum < MaxLecturer) {
System.out.println("true");
return true;
}
else {
System.out.println("false");
return false;
}
}
The function does not work properly, It always returns true (because that the Max Lecturer always bigger than sum).
main:
public class main {
public static void main(String[]args){
Lecturer[] L1 = new Lecturer[]{new Lecturer("David",3,"Banana",1001)};
Lecturer[] L2 = new Lecturer[]{new Lecturer("Yossi",5,"apple",1002)};
Lecturer[] L3 = new Lecturer[]{new Lecturer("Y",2,"t",1003)};
College myCollege = new College("College1",20,L1,3);
//System.out.println(myCollege);
//myCollege.allLecturer=L2;
//System.out.println(myCollege);
myCollege.newLecturer(L1);
myCollege.newLecturer(L2);
myCollege.newLecturer(L3);
}
}
class College (Function here):
public class College {
public String name;
public int numOfLecturer;
public Lecturer[] allLecturer;
public int maxLecturer;
// constructor
public College(String Name, int NumOfLecturer, Lecturer[] AllLecturer,
int MaxLecturer) {
this.name = Name;
this.numOfLecturer = NumOfLecturer;
this.allLecturer = AllLecturer;
this.maxLecturer = MaxLecturer;
}
public College(String Name) {
this.name = Name;
}
public College(Lecturer[] AllLecturer) {
this.allLecturer = AllLecturer;
}
public boolean newLecturer(Lecturer[] AllLecturer) {
int MaxLecturer = 0;
MaxLecturer = this.maxLecturer;
int sum = 0;
sum += 1;
if (sum < MaxLecturer) {
System.out.println("true");
return true;
}
else {
System.out.println("false");
return false;
}
}
#Override
public String toString() {
String lecturers = "";
for (Lecturer lecturer : allLecturer) {
lecturers += lecturer;
}
return "[Name College: " + name + "] " + " [num Of Lecturer: "
+ numOfLecturer + "]" + " [all Lecturer: " + lecturers + "]"
+ " [max Lecturer " + maxLecturer + "]";
}
}
class Lecturer:
public class Lecturer {
public String name;
public int numOfTimesPenFalls;
public String favoriteIceCream;
public int autoNumber;
// constructor
public Lecturer(String Name, int NumOfTimesPenFalls,
String FavoriteIceCream, int AutoNumber) {
this.name = Name;
this.numOfTimesPenFalls = NumOfTimesPenFalls;
this.favoriteIceCream = FavoriteIceCream;
this.autoNumber = AutoNumber;
}
public Lecturer(String Name) {
this.name = Name;
}
#Override
public String toString() {
return "[name: " + name + "] " + " [num Of Times Pen Falls: "
+ numOfTimesPenFalls + "] " + " [favorite Ice Cream: "
+ favoriteIceCream + "] " + " [auto Number: " + autoNumber
+ "]";
}
}
And finally how can I print it?
Like this gives a compiler error:
myCollege.newLecturer("David",2,"Apple",1004);
thank you.
You're new; you need a lot of help.
Start by learning and following Java coding standards. Variable names should start with lower case. Classes start with upper. Deviations from that make your code hard to read.
Your method is wrong. You need something like this inside that class:
private static final int MAX_LECTURERS = 3;
private int numLecturers = 0;
private Lecturer [] lecturers = new Lecturer[MAX_LECTURERS];
public boolean addLecturer(Lecturer lecturer) {
boolean addedLecturer = false;
if (this.numLecturers < MAX_LECTURERS) {
this.lecturers[numLecturers++] = lecturer;
addedLecturer = true;
}
return addedLecturer;
}
Here's how you use this method:
Lecturer newLecturer = new Lecturer("foo", 1, "bar", 3);
college.addLecturer(newLecturer);
Please stop with all that array nonsense. The array is inside the College class.
The sum variable in your code is a local variable, its scope is only at the function level. This means the sum always get initialized to 0 and increased to 1 every time the function newLecturer() is called. That's why sum always smaller than MAX_LECTURER (1<3).
You need to use class variable numLecturers like in duffymo answer above.
I am creating a program that simulates some people catching fish in a lake, I already created classes for Fish and Pond and I was working on the Fisher class and a method is not working and I'll show the code (I'm new to programming so I'm not sure if I am providing enough information)
public class Fisher {
public static int LIMIT = 3;
private String name;
private Fish[] fishCaught = new Fish[LIMIT];
private int numFishCaught;
private int keepSize;
public Fisher(String name, Fish[] fishCaught, int numFishCaught, int keepSize) {
this.name = name;
this.fishCaught = fishCaught;
this.numFishCaught = numFishCaught;
this.keepSize = keepSize;
}
public String getName() {
return name;
}
public Fish[] getFishCaught(){
return fishCaught;
}
public int getNumFishCaught() {
return numFishCaught;
}
public int getKeepSize() {
return keepSize;
}
public String toString() {
return (name + " with " + numFishCaught + " fish");
}
public void keep(Fish f) {
if (numFishCaught == LIMIT) {
} else {
numFishCaught++;
fishCaught[numFishCaught-1] = f;
}
}
boolean likes(Fish f) {
if ((f.getSize() >= keepSize) && !(f.getSpecies().equalsIgnoreCase("Sunfish"))) {
return true;
}
return false;
}
public void listFish(){
System.out.println(name + " with " + numFishCaught + " as follows: ");
for (int i = 0; i<numFishCaught; i++){
Fish f = new fish[i];
System.out.println("A " + f.getSize() + " cm " + f.getFishCaught());
}
}
}
the problem is the listFish() method, it's supposed to return something like this:
Bob with 2 fish as follows:
A 4 cm Pike
A 15 cm Bass
but it's not working it gives me "incompatible types" and "cannot find symbol" errors??
(just to make your life easier i'll include the Fish class too)
public class Fish {
private String species;
private int size;
public Fish(int size, String species) {
this.size = size;
this.species = species;
}
public String toString() {
return " A " + size + " cm " + species;
}
public String getSpecies() {
return species;
}
public int getSize() {
return size;
}
}
Error: /Users/halahalhomoud/Fisher.java:57: incompatible types
found : Fish[]
required: Fish
File: /Users/halahalhomoud/Fisher.java [line: 58]
Error: /Users/halahalhomoud/Fisher.java:58: cannot find symbol
EDIT:
show you how? I used it in the Pond class and it worked fine but I don't get why it's not working here.
You want the fish that are caught by a Fisher. Now, you have that information in the array you can retrieve with getFishCaught.
Now look what you try to do instead:
Fish f = new fish[i];
System.out.println("A " + f.getSize() + " cm " + f.getFishCaught());
In the first line, you try to make a new array of fish, but it is, of course Fish (fish is the symbol that couldn't get resolved.). Then you try to assign the array reference to a single Fish f. But an array of Fish is not the same as a Fish. For example, you can eat a Fish, but not a Fish container, you know.
What you probably want is this:
Fish f = (getFishCaught())[i]; // get the i-th Fish caught
System.out.println("A " + f.getSize() + " cm " + f.getXXX());
where getXXX is a method of Fish that returns the Fishs species. (Since you didn't show the FIsh class, I can't know the exact name of this getter).
Fish f = new fish[i];
should be:
Fish f = fishCaught[i];
Complete Method
public void listFish(){
System.out.println(name + " with " + numFishCaught + " as follows: ");
for (int i = 0; i<numFishCaught; i++){
if(fishCaught[i] != null){
Fish f = fishCaught[i];
System.out.println("A " + f.getSize() + " cm " + f.getSpecies());
}
}
}
I have a program that interprets and sorts data for a car dealer, and there is an error when trying to retrieve the color of the cars stored in an array.
Here is the main class and its sub class.
class Car
{
protected String model;
protected int price;
protected int year;
public Car(String m, int y, int p)
{
model = m;
price = p;
year = y;
}
}
class NewCar extends Car
{
protected String color;
public NewCar(String m, int y, int p, String c)
{
super(m, y, p);
color = c;
}
public String toString()
{
return "Model: " + model + "\n"
+ "Year: " + year + "\n"
+ "Price: $" + price + "\n"
+ "Color: " + color + "\n"
+ "Selling Price: " + price + "\n\n";
}
}
Here is another class in which the error occurs, at if(cars[z].color.equals(shade)).
The program cannot find variable color in class Car.
class CarDealerShip
{
public String printAllCarsOfColor(String shade)
{
String s = "";
for(int z = 0; z < i; z++)
{
if(cars[z].color.equals(shade))
{
s += "Car " + (z + 1) + "\n" + cars[z].toString();
}
}
return s;
}
How can I have the program look in class NewCar where variable color exists?
Your array cars appears to be of type Car[]. With a reference variable of Car after you have referenced the array element, there is no way to tell if it refers to a Car, a NewCar, or another subclass of Car.
It looks like you expect cars[z] to have the attribute color, so perhaps cars should be of type NewCar[] instead of Car[].
Another option is to move the attribute color to the superclass Car so any Car can have a color.
When using protected access the field will be available in classes that are within the same package or are a subclass of the base class. I'm assuming the class CarDealerShip which accesses the color field is not within the same package or does not extend Car.
The color is protected in NewCar. You can access protected variable only in sub classes. You need to move color to Car and add a public String getColor() method in your Car to make it available for the classes which are not part of the Car inheritance hierarchy.
public String getColor() {
return color;
}
and then your condition would be
if(cars[z].getColor().equals(shade))
Update
In case you want color to be in NewCar, you should add the public String getColor(); method in NewCar and your cars[] should be NewCar[], something like,
NewCar cars[] = new NewCar[arraySize]();
with this you will loose the inheritance capabilities, you can not use Car cars[] = new NewCar[arraySize] anymore.
If it's a requirement that color has to be in class NewCar you could use the instanceof operator and then cast it:
class CarDealerShip
{
public String printAllCarsOfColor(String shade)
{
String s = "";
for(int z = 0; z < i; z++)
{
if (cars[z] instanceof NewCar)
{
NewCar nc = (NewCar)cars[z];
if (nc.color.equals(shade))
{
s += "Car " + (z + 1) + "\n" + nc.toString();
}
}
}
return s;
}
}
You actually skip every Car that it not a NewCar and use only those that are an instance of the class NewCar.