basic constructor usage in java - java

For whatever reason, I cannot find this question anywhere else, nor can I find the answer online. If I have the following:
package temp1;
public class MainClass {
public static void main(String[] args) {
}
public MainClass(int radius_x, int area_x, int circumference_x) {
int radius = radius_x;
int area = area_x;
int circumference = circumference_x;
}
}
Assuming that this is even correct usage, then how would I actually use the variables defined in the constructor here? They only work inside of the constructor thanks to scope.

You are correct that the code you supply makes little sense. A more common scenario is to use the constructor to initialize a few instance variables, which can then be used throughout the class.
public class MainClass {
private int radius;
private int area;
private int circumference;
public static void main(String[] args) {
}
public MainClass(int radius_x, int area_x, int circumference_x) {
this.radius = radius_x;
this.area = area_x;
this.circumference = circumference_x;
}
}

One way to re-use the arguments of your constructor is to have instance variables assigned with your constructor's arguments' values.
As such:
package temp1;
public class MainClass {
private int radiusX;
private int areaX;
private int circumferenceX;
public static void main(String[] args) {
}
public MainClass(int radius_x, int area_x, int circumference_x) {
this.radiusX = radius_x;
this.areaX = area_x;
this.circumferenceX = circumference_x;
}
// TODO getters [and setters] for instance variables
}

package temp1;
public class MainClass {
int radius ;
int area;
int circumference;
public static void main(String[] args) {
}
public MainClass(int radius_x, int area_x, int circumference_x) {
this.radius = radius_x;
this.area = area_x;
this.circumference = circumference_x;
}
}

You created a constructor, but the variables inside are only local to the constructor itself and not outside of it. To do this, you need class member fields:
public class MainClass {
private int radius;
private int area;
private int circumference;
public static void main(String[] args) throws Exception {
MainClass m = new MainClass(5, 6, 7);
System.out.println("The radius is " + m.getRadius());
}
public MainClass(int radius_x, int area_x, int circumference_x) {
radius = radius_x;
area = area_x;
circumference = circumference_x;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public int getArea() {
return area;
}
public void setArea(int area) {
this.area = area;
}
public int getCircumference() {
return circumference;
}
public void setCircumference(int circumference) {
this.circumference = circumference;
}
}
Keep in mind also there is no need to pass in area_x and circumference_x Those can be derived from radius_x. That's assuming you are being faithful to the meanings of the terms rather than just playing around with variables to learn the language.

Related

Shadowed Final Fields

So i am trying to generate a house(at this point a very simple house) and I have this Class:
public class Probability {
public final int MinWindows = 0;
public final int MaxWindows = 0;
//double values represend the percent chance for a specific attribute to
//generate
public final double hasBackDoor = 0;
public final double hasSecondFloor = 0;
public final double hasChimny = 0;
public final double hasGarage = 0;
public final double hasPorch = 0;
}
This class is then inherited by subclasses for different types of houses:
public class LowClassHouseProbability extends Probability{
public final int MinWindows = 5;
public final int MaxWindows = 10;
public final double hasBackDoor = 55.0;
public final double hasSecondFloor = 10.0;
public final double hasChimny = 5.5;
public final double hasGarage = 30.0;
public final double hasPorch = 60.0;
}
public class MiddleClassHouseProbability extends Probability{
public final int MinWindows = 20;
public final int MaxWindows = 50;
public final double hasBackDoor = 80.0;
public final double hasSecondFloor = 70.0;
public final double hasChimny = 10.0;
public final double hasGarage = 90.0;
public final double hasPorch = 85.0;
}
public class UpperClassHouseProbability extends Probability{
public final int MinWindows = 50;
public final int MaxWindows = 100;
public final double hasBackDoor = 100.0;
public final double hasSecondFloor = 100.0;
public final double hasChimny = 80.0;
public final double hasGarage = 99.0;
public final double hasPorch = 100.0;
}
So all of the subclasses of Probability shadow all of its fields which in my opinioin looks sloppy and is kind of annoying to read, however i need them to extend Probability because it would make it easyer when i actually have to use the object, because it looks nicer doing this:
public class House {
public House(Probability prob){
}
}
Than if i did not have a Probability class and did this:
public class House {
public House(LowClassHouseProbability prob){
}
public House(MiddleClassHouseProbability prob){
}
public House(UpperClassHouseProbability prob){
}
}
And this would only get worse with the more sub-classes that I create.
So my question is is there a better way of doing this that I'm not thinking of, or do i just have to do it one way or the other of the two solutions that I thought of.
Since you can not override fields from the super class in java those classes dont need at all to define the field..
public class LowClassHouseProbability extends Probability{
//public final int MinWindows = 50;
//public final int MaxWindows = 100;
those all are final declared so you need to set those in the constructor...
LowClassHouseProbability(int minW, int maxW,...){
super(minW, maxW, ....);
MiddleClassHouseProbability(int minW, int maxW,...){
super(minW, maxW, ....);
UpperClassHouseProbability(int minW, int maxW,...){
super(minW, maxW, ....);
and in the superclass Probability define the constructor:
Probability(int minW, int maxW,...){
MinWindows = minW;
MaxWindows = maxW;
// .... etc etc
It's probably best to remove the child classes altogether and define instances of the Probability class pertinent to your house types, and build a multi-argument constructor to facilitate instance construction.
Alternatively, you could refactor this into an interface:
public interface Probability {
int getMinWindwsMinWindows();
/*and so on*/
}
Then,
public class LowClassHouseProbability implements Probability{
{
#Override
int getMinWindwsMinWindows()
{
return 5;
}
/*and so on*/
}
The problem of managing constructors with too many fields can be solved by using a step builder. A step builder works by creating an interface for each step, then having the builder implement all of them. This way after completing each build step, only the next step is available to complete.
Here's an example:
package mcve;
public class Probability {
public final int minWindows;
public final int maxWindows;
public final double hasBackDoor;
public final double hasSecondFloor;
public final double hasChimny;
public final double hasGarage;
public final double hasPorch;
private Probability(final int minWindows,
final int maxWindows,
final double hasBackDoor,
final double hasSecondFloor,
final double hasChimny,
final double hasGarage,
final double hasPorch) {
this.minWindows = minWindows;
this.maxWindows = maxWindows;
this.hasBackDoor = hasBackDoor;
this.hasSecondFloor = hasSecondFloor;
this.hasChimny = hasChimny;
this.hasGarage = hasGarage;
this.hasPorch = hasPorch;
}
public static final Probability LOW_CLASS =
builder().setMinWindows(5)
.setMaxWindows(10)
.setHasBackDoor(55.0)
.setHasSecondFloor(10.0)
.setHasChimny(5.5)
.setHasGarage(30.0)
.setHasPorch(60.0)
.build();
// public static final Probability MIDDLE_CLASS = ...;
// public static final Probability UPPER_CLASS = ...;
public static MinWindowsStep builder() {
return new Builder();
}
public interface MinWindowsStep { MaxWindowsStep setMinWindows(int n); }
public interface MaxWindowsStep { HasBackDoorStep setMaxWindows(int n); }
public interface HasBackDoorStep { HasSecondFloorStep setHasBackDoor(double n); }
public interface HasSecondFloorStep { HasChimnyStep setHasSecondFloor(double n); }
public interface HasChimnyStep { HasGarageStep setHasChimny(double n); }
public interface HasGarageStep { HasPorchStep setHasGarage(double n); }
public interface HasPorchStep { BuildStep setHasPorch(double n); }
public interface BuildStep { Probability build(); }
private static final class Builder
implements MinWindowsStep,
MaxWindowsStep,
HasBackDoorStep,
HasSecondFloorStep,
HasChimnyStep,
HasGarageStep,
HasPorchStep,
BuildStep {
private int minWindows;
private int maxWindows;
private double hasBackDoor;
private double hasSecondFloor;
private double hasChimny;
private double hasGarage;
private double hasPorch;
#Override
public MaxWindowsStep setMinWindows(int minWindows) {
this.minWindows = minWindows;
return this;
}
#Override
public HasBackDoorStep setMaxWindows(int maxWindows) {
this.maxWindows = maxWindows;
return this;
}
#Override
public HasSecondFloorStep setHasBackDoor(double hasBackDoor) {
this.hasBackDoor = hasBackDoor;
return this;
}
#Override
public HasChimnyStep setHasSecondFloor(double hasSecondFloor) {
this.hasSecondFloor = hasSecondFloor;
return this;
}
#Override
public HasGarageStep setHasChimny(double hasChimny) {
this.hasChimny = hasChimny;
return this;
}
#Override
public HasPorchStep setHasGarage(double hasGarage) {
this.hasGarage = hasGarage;
return this;
}
#Override
public BuildStep setHasPorch(double hasPorch) {
this.hasPorch = hasPorch;
return this;
}
#Override
public Probability build() {
return new Probability(minWindows,
maxWindows,
hasBackDoor,
hasSecondFloor,
hasChimny,
hasGarage,
hasPorch);
}
}
}
Fields have to be assigned by name, and if you forget which step you are on, the compiler error will tell you:
// This will cause an error with a message something like
// "Cannot find symbol method build() in interface MinWindowsStep".
Probability p = Probability.builder()
.build();
If it turns out that it really is the case that you need to use inheritance, the builder pattern can be adapted to that by having e.g. an abstract build step with multiple implementations.

Calculating discount using multiple methods within the same class

I understand that I do not have anything in my main method yet so nothing will execute, that is the second part to the assignment.
My question is, I'm getting an error in the computeDiscount method where I'm calling the computeNumCases method. The error i'm getting is
variable numCases might not have been initialized
so I need help figuring that error out.
Also, help in the computeCost method would be very helpful as well.
public class Customer {
private String customerLastName;
private String candyType;
private int numCandyBars;
private double costPerBar;
private int NUMBERPERCASE = 12;
public static void main(String[] args) {
}
public Customer() {
}
public Customer(String name, String type, int numCandyBars, double costPerBar) {
//this.name = name;
candyType = type;
this.numCandyBars = numCandyBars;
this.costPerBar = costPerBar;
}
public static double getCostPerBar(double costPerBar) {
return costPerBar;
}
public static int getNumCandyBars(int numCandyBars) {
return numCandyBars;
}
public String getCandyType() {
return candyType;
}
public String GetCustomerLastName() {
return customerLastName;
}
public void setCustomerLastName(String name) {
this.customerLastName = name;
}
public void setNumCandyBars(int num) {
this.numCandyBars = num;
}
public void setCandyType(String candyType) {
this.candyType = candyType;
}
public void setCostPerBar(double cost) {
costPerBar = cost;
}
public int computeNumCases(int numCases) {
numCases = numCandyBars / NUMBERPERCASE;
return numCases;
}
public int computeNumIndividuals(int numIndividuals) {
numIndividuals = numCandyBars % NUMBERPERCASE;
return numIndividuals;
}
public int computeDiscount(int discount) {
int numCases = computeNumCases(numCases);
if (numCases < 20)
discount = 100;
else if (numCases < 50)
discount = 85;
else
discount = 75;
return discount;
}
public double computeCost(double totalCost) {
return computeNumCases(numCases) * getCostPerBar(costPerBar) * (NUMBERPERCASE * discount / 100.00) + computeNumIndividuals(numIndividuals) * getCostPerBar(costPerBar);
}
}

Why is my java EXTENDS not working?

I hava a Super Class Ball with extender OvalBall. With following being my code I am getting a error message telling me I can't use the child class OvalBall. can anyone help explain please?
public class Ball
{
private double diameter;
private String colour;
public Ball(double d, String c)
{
this.diameter = d;
this.colour = c;
}
public void setDiameter(double d)
{
this.diameter = d;
}
public double getDiameter()
{
return this.diameter;
}
public void setColour(String c)
{
this.colour = c;
}
public String getColour()
{
return colour;
}
public double bounce()
{
double height = diameter * 2;
return height;
}
public void roll()
{
System.out.println("wheeee");
}
public class OvalBall extends Ball
{
private double secondDiameter;
public void setSecondDiameter(double sd)
{
this.secondDiameter = sd;
}
public double getSecondDiameter()
{
return this.secondDiameter;
}
}
}
public class Main
{
public static void main(String[] args)
{
OvalBall na = new OvalBall(4,"blue",4);
na.setSDiameter(10);
System.out.println(na.bounce());
}
}
Feel free to change anything.
Thanks
You need to define OvalBall either as static or in its own file.
Maybe OvalBall din't implement the constructor class of hi base class
That's why you can't create a object of OvalBall.
class Ball {//This is you base class contructor
//Child class contructor
public class OvalBall extends Ball
{
public OvalBall(double d, String c)
{
base(d,c);
}
}
And when you make nested classes in java there is a different. way to create an object instance instead of other languages Like C#.
Try in this way. or use my code as example
public class Main
{
public static void main(String[] args)
{
Ball.OvalBall na = na.new OvalBall(4,"blue",4);
na.setSDiameter(10);
System.out.println(na.bounce());
}
}

My getStats method pops up with infinity numbers

In Java, my basketball players keep sending back "infinity" in my getStats method and I do not know why. Can someone help please? I needed getters and setters so I have that. I am suppose to test the getStats() methods but it errors out every time. At first it was NaNa now its infinity
public class BasketBallPlayer
{
// instance variables - replace the example below with your own
private String name;
private int height;
private int weight;
private double freeThrowsAttempted;
private double freeThrowsMade;
private double twoPointFieldGoalsAttempted;
private double twoPointFieldGoalsMade;
private double threePointersAttempted;
private double threePointersMade;
private int turnovers;
private int assist;
private String stats;
public BasketBallPlayer(String name, int height, int weight, double freeThrowsMade, double twoPointFieldGoalsAttempted,double twoPointFieldGoalsMade, double threePointersAttempted, double threePointersMade, int assist, int turnovers)
{
//identifies the age, name, height-in., weight-lbs
this.name=name;
this.height=height;
this.weight=weight;
this.freeThrowsAttempted=freeThrowsAttempted;
this.freeThrowsMade=freeThrowsMade;
this.twoPointFieldGoalsAttempted=twoPointFieldGoalsAttempted;
this.threePointersMade=threePointersMade;
this.turnovers=turnovers;
this.assist=assist;
}
public BasketBallPlayer(int weight, int height, String name)
//identifies the weight(lbs.), height(inches) and String name
{
//identifies the name, height-in., weight-lbs
this.name=name;
this.height=height;
this.weight=weight;
}
//Sets the Name
public void setName(String name)
{
this.name=name;
}
//Sets the Height
public void setHeight (int height)
{
this.height=height;
}
//Sets the Weight
public void setWeight (int weight)
{
this.weight=weight;
}
//Sets the Free Throws Attempted
public void setFreeThrowsAttempted( double freeThrowsAttempted)
{
this.freeThrowsAttempted=freeThrowsAttempted;
}
//Sets the Free Throws Made
public void setFreeThrowsMade(double freeThrowsMade)
{
this.freeThrowsMade=freeThrowsMade;
}
// Sets two Point Field Goals Attempted
public void setTwoPointFieldGoalsAttempted (double twoPointFieldGoalsAttempted)
{
this.twoPointFieldGoalsAttempted=twoPointFieldGoalsAttempted;
}
public void setTwoPointFieldGoalsMade (double twoPointFieldGoalsMade)
{
this.twoPointFieldGoalsMade=twoPointFieldGoalsMade;
}
public void setThreePointerAttempted(double threePointersAttempted)
{
this.threePointersAttempted=threePointersAttempted;
}
public void setThreePointersMade(double threePointersMade)
{
this.threePointersMade=threePointersMade;
}
public void setTurnovers(int turnovers)
{
this.turnovers=turnovers;
}
public void setAssist(int assist)
{
this.assist=assist;
}
//Returns a Name
public String getName()
{
return name;
}
public int getHeight ()
{
return height;
}
public int getWeight ()
{
return weight;
}
public double getFreeThrowsAttempted()
{
return freeThrowsAttempted;
}
public double getfreeThrowsMade()
{
return freeThrowsMade;
}
public double getTwoPointFieldGoalsAttempted ()
{
return twoPointFieldGoalsAttempted;
}
public double getTwoPointFieldGoalsMade ()
{
return twoPointFieldGoalsMade;
}
public double getThreePointerAttempted()
{
return threePointersAttempted;
}
public double getthreePointersMade()
{
return threePointersMade;
}
public int getTurnovers()
{
return turnovers;
}
public int gettAssist()
{
return assist;
}
/** The geStats Method allows you to get all information on the player in print. All Percentages
*
*/
public void getStats()
{
double Percentage1;
double Percentage2;
double Percentage3;
Percentage1=(double)((twoPointFieldGoalsMade*100)/twoPointFieldGoalsAttempted);
Percentage2=((double)(threePointersMade*100)/threePointersAttempted);
Percentage3=((double)((freeThrowsMade*100)/freeThrowsAttempted));
System.out.println("*************************");
System.out.println("BasketBall Player Name:" + name);
System.out.println("Field Goal Percentage:" + Percentage1 +"%");
System.out.println("3 Pointer Percentage:" + Percentage2 +"%");
System.out.println("Free Throw Percentage:" + Percentage3 +"%");
System.out.println("Assist to Turnover Ration:" + assist/turnovers);
System.out.println("*************************");
}
}
First, you should not be using doubles for these number. It just accounts to inefficiency and makes no sense. However, when using ints, you have to note that you cannot directly get a percentage when dividing two ints. This piece of code should work, you may want to include some code that checks that the divisors are not 0.
private int freeThrowsAttempted;
private int freeThrowsMade;
private int twoPointFieldGoalsAttempted;
private int twoPointFieldGoalsMade;
private int threePointersAttempted;
private int threePointersMade;
...
double percentage1 = (twoPointFieldGoalsMade * 100F) / twoPointFieldGoalsAttempted;
double percentage2 = (threePointersMade * 100F) / threePointersAttempted;
double percentage3 = (freeThrowsMade * 100F) / freeThrowsAttempted;

Java Program printing infinitely before crashing

When I run javac Hero.java Then java Hero The program spits out tons of lines that look like this:
Hero#322ba3e4
Hero#4f14e777
Hero#65685e30
Hero#26ffd553
Hero#660e5025
Hero#35afe17b
What is this? Hero#322ba3e4
Then it shows,
Exception in thread "main" java.lang.StackOverflowError
at sun.nio.cs.UTF_8.updatePositions(UTF_8.java:77)
at sun.nio.cs.UTF_8$Encoder.encodeArrayLoop(UTF_8.java:564)
at sun.nio.cs.UTF_8$Encoder.encodeLoop(UTF_8.java:619)
at java.nio.charset.CharsetEncoder.encode(CharsetEncoder.java:561)
at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:271)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:125)
at java.io.OutputStreamWriter.write(OutputStreamWriter.java:207)
at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:129)
at java.io.PrintStream.write(PrintStream.java:526)
at java.io.PrintStream.print(PrintStream.java:669)
at java.io.PrintStream.println(PrintStream.java:823)
at Hero.DrowRanger(Hero.java:78)
at Hero.DrowRanger(Hero.java:79)
This line repeats 100s of times:
at Hero.DrowRanger(Hero.java:79)
This is the method at that line,
private static Object DrowRanger() {
Hero DrowRanger = new Hero(
0,
"Agility",
"Ranged",
"Frost Arrows",
"Gust",
"Precision Aura",
"Marksmanship",
17,
1.9,
26,
1.9,
15,
1.4,
473,
195,
44,
55,
625,
0.64,
300);
System.out.println(DrowRanger);
return DrowRanger(); // Line 79 Is Here
}
This is the full class
public class Hero implements NPC {
private int level;
private String primaryAttribute;
private String attackType;
private String ability1;
private String ability2;
private String ability3;
private String ability4;
private double strength;
private double strengthMultiplier;
private double agility;
private double agilityMultiplier;
private double intelligence;
private double intelligenceMultiplier;
private int health;
private int mana;
private int damageMin;
private int damageMax;
private int range;
private double armor;
private int movement;
//default constructor
public Hero(
int level,
String primaryAttribute,
String attackType,
String ability1,
String ability2,
String ability3,
String ability4,
double strength,
double strengthMultiplier,
double agility,
double agilityMultiplier,
double intelligence,
double intelligenceMultiplier,
int health,
int mana,
int damageMin,
int damageMax,
int range,
double armor,
int movement
) {
} // End Constructor
public static void main (String[] args) {
DrowRanger();
}
private static Object DrowRanger() {
Hero DrowRanger = new Hero(
0,
"Agility",
"Ranged",
"Frost Arrows",
"Gust",
"Precision Aura",
"Marksmanship",
17,
1.9,
26,
1.9,
15,
1.4,
473,
195,
44,
55,
625,
0.64,
300);
System.out.println(DrowRanger);
return DrowRanger();
}
// getters and setters - required to implement ALL from interface
public int getLevel() {
return this.level;
}
public String getPrimaryAttribute() {
return this.primaryAttribute;
}
public String getAttackType() {
return this.attackType;
}
public String getAbility1() {
return this.ability1;
}
public String getAbility2() {
return this.ability2;
}
public String getAbility3() {
return this.ability3;
}
public String getAbility4() {
return this.ability4;
}
public double getStrength() {
return this.strength;
}
public double getStrengthMultiplier() {
return this.strengthMultiplier;
}
public double getAgility() {
return this.agility;
}
public double getAgilityMultiplier() {
return this.agilityMultiplier;
}
public double getIntelligence() {
return this.intelligence;
}
public double getIntelligenceMultiplier() {
return this.intelligenceMultiplier;
}
public int getHealth() {
return this.health;
}
public int getMana() {
return this.mana;
}
public int getDamageMin() {
return this.damageMin;
}
public int getDamageMax() {
return this.damageMax;
}
public int getRange() {
return this.range;
}
public double getArmor() {
return this.armor;
}
public int getMovement() {
return this.movement;
}
// This is where the setters are.
public void setLevel(int level) {
this.level = level;
}
public void setPrimaryAttribute(String primaryAttribute) {
this.primaryAttribute = primaryAttribute;
}
public void setAttackType(String attackType) {
this.attackType = attackType;
}
public void setAbility1(String ability1) {
this.ability1 = ability1;
}
public void setAbility2(String ability2) {
this.ability2 = ability2;
}
public void setAbility3String(String ability3) {
this.ability3 = ability3;
}
public void setAbility4(String ability4) {
this.ability4 = ability4;
}
public void setStrength(double strength) {
this.strength = strength;
}
public void setStrengthMultiplier(double strengthMultiplier) {
this.strengthMultiplier = strengthMultiplier;
}
public void setAgility(double agility) {
this.agility = agility;
}
public void setAgilityMultiplier(double agilityMultiplier) {
this.agilityMultiplier = agilityMultiplier;
}
public void setIntelligence(double intelligence) {
this.intelligence = intelligence;
}
public void setIntelligenceMultiplier(double intelligenceMultiplier) {
this.intelligenceMultiplier = intelligenceMultiplier;
}
public void setHealth(int health) {
this.health = health;
}
public void setMana(int mana) {
this.mana = mana;
}
public void setDamageMin(int damageMin) {
this.damageMin = damageMin;
}
public void setDamageMax(int damageMax) {
this.damageMax = damageMax;
}
public void setRange(int range) {
this.range = range;
}
public void setArmor(double armor) {
this.armor = armor;
}
public void setMovement(int movement) {
this.movement = movement;
}
} // End Character Class
`
Your DrowRanger method is calling itself infinitely. This is almost always the cause of a StackOverflowException.
This line:
return DrowRanger();
Calls the DrowRanger method, but since you're inside the DrowRanger method it just keeps calling itself infinitely. I think you meant to return the local object:
return DrowRanger;
In general, it is a bad idea to give methods and objects the same name. Also, it is java convention always start method and variable/field names with a lowercase letter.
The output you're seeing is how java prints objects that have not overridden the toString() method. See this post for an explanation of how the toString() method works.
To the first: println prints the output of the toString method of the object. As it is just the normal method inherited by the Object class it just returns the name of the class and the hash of the object.
To your error: it looks like there is an infinite loop somewhere (which has been found).

Categories