Can't get a basic method to work - java

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.

Related

java - Function in class

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.

Converting the same String value into an Object

I have an object share:
Share tea = new Share("TEA", "Common", 0, 100);
ArrayList<Share> shares = new ArrayList<Share>();
shares.add(tea);
What I'd like to do is, reading parameters from the keybord, convert directly the "tea" string into a share tea object :
Trade trade = new Trade( tea, Boolean.parseBoolean(buyOrSell), Integer.parseInt(quantity), Double.parseDouble(tradePrice));
What should I put instead of tea because my constructor is waiting a Share and not a String. The user is entering a string and I don't need ton create a new instance, I have to use the Share object "tea" that already exists.
The Share.java class :
public class Share {
private String shareSymbol = "";
private String type = "Common";
private double lastDividend = 0;
private double fixedDividend = 0;
private int parValue = 0;
// Calucul values
public String getShareSymbol() {
return shareSymbol;
}
public String getType() {
return type;
}
public double getLastDividend() {
return lastDividend;
}
public double getFixedDividend() {
return fixedDividend;
}
public int getParValue() {
return parValue;
}
// Constructor without Fixed Dividend
public Share(String shareSymbol, String type, int lastDividend, int parValue) {
this.shareSymbol = shareSymbol;
this.type = type;
this.lastDividend = lastDividend;
this.parValue = parValue;
}
// Constructor with Fixed Dividend
public Share(String shareSymbol, String type, int lastDividend,
int fixedDividend, int parValue) {
this(shareSymbol, type, lastDividend, parValue);
this.fixedDividend = fixedDividend / 100.0;
}
public String toString(){
String result="";
result += shareSymbol + " "+type + " " + lastDividend + " " + fixedDividend + " " + parValue + "\n";
return result;
}
}
The Trade.java class :
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
// The class trade allows the stock, the quantity and the price to be intialised
public class Trade {
Share share;
private int quantity;
double price;
private double dividendYield;
private double pERatio;
private boolean buyOrSell;
private Date tradeDate;
public Trade(Share share, boolean buyOrSell, int quantity, double price) {
this.share = share;
this.buyOrSell = buyOrSell;
this.quantity = quantity;
this.price = price;
tradeDate = Calendar.getInstance().getTime();
}
public String toString() {
String result = "";
result += "stock symbol : " + share.getShareSymbol() + " \n";
result += "Buy or Sell : " + buyOrSell + " \n";
result += "quantity :" + quantity + " \n";
result += "price : " + price + " \n";
result += "Dividend Yield : " + dividendYield + " \n";
result += "P/E Ratio : " + pERatio + " \n";
result += "tradeDate : " + tradeDate + " \n\n";
return result;
}
public Share getShare() {
return share;
}
public int getQuantity() {
return quantity;
}
public double getPrice() {
return price;
}
public double getDividendYield() {
return dividendYield;
}
public double getpERatio() {
return pERatio;
}
public Date getTradeDate() {
return tradeDate;
}
public double calcDividendYield() {
if ("Common".equalsIgnoreCase(share.getType())) {
dividendYield = share.getLastDividend() / price;
} else if ("Preferred".equalsIgnoreCase(share.getType())) {
dividendYield = share.getFixedDividend() * share.getParValue()
/ price;
}
return dividendYield;
}
public double calcPERatio() {
if (dividendYield > 0)
pERatio = price / dividendYield;
return pERatio;
}
}
Your constructor is waiting a share. So give it:
/* Read parameters from keyboard, stock in s1, s2, i1 and i2 variables */
Trade trade = new Trade( new Share(s1,s2,i1,i2), Boolean.parseBoolean(buyOrSell), Integer.parseInt(quantity), Double.parseDouble(tradePrice));
Otherwise you can implement a method (in Share class) that do it for you
public static Share stringToShare(String s1, String s2, int t1, int t2){
return new Share(s1, s2, t1, t2);
}
And then:
Trade trade = new Trade( Share.stringToShare(...), Integer.parseInt(quantity), Double.parseDouble(tradePrice));
EDIT: better use real variable names that means something, not s1, s2, etc.
I've got around of this, by creating a new constructor :
Trade trade = new Trade(shares, stockSymbol, Boolean.parseBoolean(buyOrSell),
Integer.parseInt(quantity), Double.parseDouble(tradePrice));
This is then the new constructor :
public Trade(ArrayList<Share> shares, String stockSymbol,
boolean buyOrSell, int quantity, double price) {
Iterator<Share> iter = shares.iterator();
int index = -1;
while (iter.hasNext()) {
Share share = iter.next();
index++;
if (stockSymbol.equalsIgnoreCase((share.getShareSymbol()))) {
this.share = shares.get(index);
this.buyOrSell = buyOrSell;
this.quantity = quantity;
this.price = price;
tradeDate = Calendar.getInstance().getTime();
break;
}
}
}
It's a bit complacated, because I had also to create a new method to get the Share for the given String(having the same name, for instance). But that does What i needed.
It would be cleaner though to make it with Java Reflection, without having to create a new constructor. So if any one have an idea with a code more clever, I would be happy!

my dog trithlon program gives errors

public class DogTriathlonParticipant {
/**
* #param args the command line arguments
*/
static {
}
public static void main(String[] args) {
{
{
private static int NUM_EVENTS;
private static int totalCumulativeScore = 0;
private final string name;
private final int obedienceScore;
private final int conformationScore;
private final int agilityScore;
private final int total;
private final double avg;
private String name;
public DogTriathlonParticipant (String name, int numEvents, int score1,
int score2, int score3)
{
{
{
{
this.name = name;
NUM_EVENTS = numEvents;
obedienceScore = score1;
conformationScore = score2;
agilityScore = score3;
total = obedienceScore + conformationScore + agilityScore;
avg = (double) total / NUM_EVENTS;
totalCumulativeScore = totalCumulativeScore + total;
{
{
{
}
}
}
{
public void display()
{
System.out.println(name + " participated in " + NUM_EVENTS + " Events and has an average score of " + avg);
System.out.println( " " + name + " has total score of " + total + " bringing the total cumlative score to " + totalCumulativeScore);
}
public class TestDogs
{
}
public static void main(String[] args)
{
{
{
DogTriathlonParticipant dog1 =
new DogTriathlonParticipant("Bowser" , 2, 85, 89,0);
dog1.display();
{
}
DogTriathlonParticipant dog2 =
new DogTriathlonParticipant("Rush", 3, 78, 72, 80);
dog2.display();
{
}
DogTriathlonParticipant dog3 =
new DogTriathlonParticipant("Ginger", 3, 90, 86, 72);
dog3.display();
}
}
}
}
it keeps giving errors to my names and string and also the public voids
maybe I just need a fresh eye to help me figure out the errors and why they say they are illegal
and fi you could figure it out can you also explain to me why so I can learn why?
I'm using netbeans and rather new to java
If you goal is to create DogTriathlonParticipant instances and "test" the instanciation by displaying the information, you may first separate your logic in different java classes / pages.
You should create new Java class in netbeans for the main, and the DogTriathlonParticipant class. To do so, click on Source Packages > new > Java Class.
Name that class DogTriathlonParticipant as show below :
public class DogTriathlonParticipant {
//private static int NUM_EVENTS;
//private static int totalCumulativeScore = 0; //this logic is not part of DogTriathlonParticipant.
// you should not put final if you plan to edit the variable.
private String name;
private int obedienceScore;
private int conformationScore;
private int agilityScore;
private int total;
private double avg;
private String name;
public DogTriathlonParticipant (String name, int numEvents, int score1, int score2, int score3) {
this.name = name;
// NUM_EVENTS = numEvents; this logic don't belong here
obedienceScore = score1;
conformationScore = score2;
agilityScore = score3;
total = obedienceScore + conformationScore + agilityScore;
avg = (double) total / numEvents; // edited here, I think you are trying to get the average of to total by numEvents, in this case, the score1 shoulb be the sum of the events "numEvents".
//totalCumulativeScore = totalCumulativeScore + total;
}
public void display()
{
System.out.println(name + " participated in " + numEvents+ " Events and has an average score of " + avg);
System.out.println( " " + name + " has total score of " + total + " bringing the total cumlative score to " + total);
}
}
Then you should have your "test" class like this :
public class TestDogs {
public static void main(String[] args) {
DogTriathlonParticipant dog1 = new DogTriathlonParticipant("Bowser" , 2, 85, 89,0);
DogTriathlonParticipant dog2 = new DogTriathlonParticipant("Rush", 3, 78, 72, 80);
DogTriathlonParticipant dog3 = new DogTriathlonParticipant("Ginger", 3, 90, 86, 72);
dog1.display();
dog2.display();
dog3.display();
}
}
With that, you should have a good base to start and add your logic and correct the one in place.

Syntax errors in pizza order program

Can anybody help me with this?
simple pizza order program
I tried to run it in commandpromt and there are a lot of error
I have tried to change the double into int.. but the result is still error
<pre>
public class PizzaOrder
{
public static final String PIZZA_SMALL = "S";
public static final String PIZZA_MEDIUM = "M";
public static final String PIZZA_LARGE = "L";
public static final String PIZZA_COLLOSAL = "C";
public static final double SMALL_DIAMETER = 9;
public static final double MEIDUM_DIAMETER = 13;
public static final double LARGE_DIAMETER = 17;
public static final double COLOSSAL_DIAMETER = 26;
public static final double PRICE_SMALL = 8;
public static final double PRICE_MEDIUM = 11;
public static final double PRICE_LARGE = 15;
public static final double PRICE_COLOSSAL = 21;
public static final double PRICE_TAX = 0.095;
public static final double PRICE_TOPPING = 0.99;
public static final int MAX_TOPPINGS = 8;
public static final int MIN_TOPPINGS = 0;
/**
* Pizza Order
*
* #param args command-line arguments
*/
public static int getDiameter(String pizzaName)
{
if (pizzaName.equals(PIZZA_SMALL))
{
return SMALL_DIAMETER;
}
else if (pizzaName.equals(PIZZA_MEIDUM))
{
return MEDIUM_DIAMETER;
}`enter code here`
else if (pizzaName.equals(PIZZA_LARGE))
{
return LARGE_DIAMETER;
}
else
{
return COLOSSAL_DIAMETER;
}
}
public static int getBasePrice(String pizzaName)
{
if (pizzaName.equals(PIZZA_SMALL))
{
return PRICE_SMALL;
}
else if (pizzaName.equals(PIZZA_MEIDUM))
{
return PRICE_MEDIUM;
}
else if (pizzaName.equals(PIZZA_LARGE))
{
return PRICE_LARGE;
}
else
{
return PRICE_COLOSSAL;
}
}
there are error about the scanner too idk why
there are 13-20 errors and mostly because of the variables PIZZA_SMALL, etc
some errors say "incompetible types" and the other says "cannot find symbol"
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter The Size of Pizza you"
+ "want: (S/M/L/C)");
String option = keyboard.nextLine().trim().substring(0,
1).toUppercase();
double pizzaPrice;
double pizzaSize;
if(option.equals(PIZZA_SMALL))
{
pizzaPrice = SMALL_DIAMETER;
pizzaSize = SMALL_DIAMETER;
}
else if (option.equals(PIZZA_MEIDUM))
{
pizzaPrice = PRICE_MEDIUM;
pizzaSize = MEDIUM_DIAMETER;
}
else if (option.equals(PIZZA_LARGE))
{
pizzaPrice = PRICE_LARGE;
pizzaSize = LARGE_DIAMETER;
}
else
{
option = PIZZA_COLOSSAL;
pizzaPrice = PRICE_COLOSSAL;
pizzaSize = COLOSSAL_DIAMETER;
}
System.out.println("Pizza Size: " + option);
System.out.println("Enter The Number of Toppings" +
"you want:(0-8)");
int pizzaTopping = keyboard.nextInt();
if(pizzaTopping < MIN_TOPPINGS)
{
pizzaTopping = MIN_TOPPINGS;
}
else if(pizzaTopping > MAX_TOPPINGS)
{
pizzaTopping = MAX_TOPPINGS;
}
else
{
pizzaTopping = pizzaTopping;
}
int radius = getDiameter(option) / 2;
double squareInches = radius * radius * Math.PI;
System.out.println("Pizza Size: " + option + "( " + pizzaSize +
"inch -- " + squareInches + " square inches)" );
System.out.println("Toppings: " + pizzaTopping);
double priceWithToppings = getBasePrice(option) + pizzaTopping * 9;
System.out.println("Price: " + priceWithToppings);
double pizzaTax = priceWithToppings * PRICE_TAX;
System.out.println("Tax: "+ pizzaTax);
double totalPrice = priceWithToppings + pizzaTax;
System.out.println("Total Price: " + totalPrice);
double priceEachSquareInch = priceWithToppings / squareInches;
System.out.println("Price/sq.in.: " + priceEachSquareInch);
}
}
Your PizzaOrder class should be as follows:
public class PizzaOrder {
public static final String PIZZA_SMALL = "S";
public static final String PIZZA_MEDIUM = "M";
public static final String PIZZA_LARGE = "L";
public static final String PIZZA_COLLOSAL = "C";
public static final double SMALL_DIAMETER = 9;
public static final double MEDIUM_DIAMETER = 13;
public static final double LARGE_DIAMETER = 17;
public static final double COLOSSAL_DIAMETER = 26;
public static final double PRICE_SMALL = 8;
public static final double PRICE_MEDIUM = 11;
public static final double PRICE_LARGE = 15;
public static final double PRICE_COLOSSAL = 21;
public static final double PRICE_TAX = 0.095;
public static final double PRICE_TOPPING = 0.99;
public static final int MAX_TOPPINGS = 8;
public static final int MIN_TOPPINGS = 0;
/**
* Pizza Order
*
* #param args
* command-line arguments
*/
public static double getDiameter(String pizzaName) {
if (pizzaName.equals(PIZZA_SMALL)) {
return SMALL_DIAMETER;
} else if (pizzaName.equals(PIZZA_MEDIUM)) {
return MEDIUM_DIAMETER;
} else if (pizzaName.equals(PIZZA_LARGE)) {
return LARGE_DIAMETER;
} else {
return COLOSSAL_DIAMETER;
}
}
public static double getBasePrice(String pizzaName) {
if (pizzaName.equals(PIZZA_SMALL)) {
return PRICE_SMALL;
} else if (pizzaName.equals(PIZZA_MEDIUM)) {
return PRICE_MEDIUM;
} else if (pizzaName.equals(PIZZA_LARGE)) {
return PRICE_LARGE;
} else {
return PRICE_COLOSSAL;
}
}
}
Notice how I corrected the return type from int to double on getDiameter and getBasePrice, as the constants you are trying to return are double. I also fixed the misspelling of "Medium" in some places.
To fix the scanner error, you must import it's package using: (Add this at the top of the file)
import java.util.Scanner;
You main method should look like this: (Again, misspelling variables and casting errors)
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter The Size of Pizza you" + "want: (S/M/L/C)");
String option = keyboard.nextLine().trim().substring(0,1).toUpperCase();
double pizzaPrice;
double pizzaSize;
if(option.equals(PIZZA_SMALL))
{
pizzaPrice = SMALL_DIAMETER;
pizzaSize = SMALL_DIAMETER;
}
else if (option.equals(PIZZA_MEDIUM))
{
pizzaPrice = PRICE_MEDIUM;
pizzaSize = MEDIUM_DIAMETER;
}
else if (option.equals(PIZZA_LARGE))
{
pizzaPrice = PRICE_LARGE;
pizzaSize = LARGE_DIAMETER;
}
else
{
option = PIZZA_COLLOSAL;
pizzaPrice = PRICE_COLOSSAL;
pizzaSize = COLOSSAL_DIAMETER;
}
System.out.println("Pizza Size: " + option);
System.out.println("Enter The Number of Toppings" +
"you want:(0-8)");
int pizzaTopping = keyboard.nextInt();
if(pizzaTopping < MIN_TOPPINGS)
{
pizzaTopping = MIN_TOPPINGS;
}
else if(pizzaTopping > MAX_TOPPINGS)
{
pizzaTopping = MAX_TOPPINGS;
}
double radius = getDiameter(option) / 2;
double squareInches = radius * radius * Math.PI;
System.out.println("Pizza Size: " + option + "( " + pizzaSize +
"inch -- " + squareInches + " square inches)" );
System.out.println("Toppings: " + pizzaTopping);
double priceWithToppings = getBasePrice(option) + pizzaTopping * 9;
System.out.println("Price: " + priceWithToppings);
double pizzaTax = priceWithToppings * PRICE_TAX;
System.out.println("Tax: "+ pizzaTax);
double totalPrice = priceWithToppings + pizzaTax;
System.out.println("Total Price: " + totalPrice);
double priceEachSquareInch = priceWithToppings / squareInches;
System.out.println("Price/sq.in.: " + priceEachSquareInch);
}
}
If you want to cast a double to an int, you need to do int something = (int)myDouble. Also pay attention when writing your variable names, as they must be exactly the same as the definition or they will throw an error. Also, if a method returns an int, but you try and return a double, it will result in an error, as the return type must be the same as what is defined in the method.
Firstly, take a good look through your code as many of your errors are typos - e.g. toUppercase(), COLLOSAL etc.
And, as per Ben's comment you are using doubles for your constants but then your methods are all integers. Java won't let you do this automatically as it results everything after the decimal point being lost as integers are whole numbers only.
When these two things are changed your code appears to work - at a quick glimpse at least.

toString return different values

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.

Categories

Resources