My getStats method pops up with infinity numbers - java

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;

Related

To set an condition for the canvas Height and Width which can't be negative?

Create the following two sub-classes that extend your Artwork class from exercise 1.
Sculpture that has the properties:
Material
Weight
Painting that has the properties:
Paint Type (e.g. watercolour, acrylic, oil)
Canvas width
Canvas height
Add relevant constructors (using super), getters and setters to your Sculpture and Painting
classes. Your painting and sculpture classes must extend the base Artwork class. In your
setters add validation for canvas width, weight and canvas height to prevent an artwork
existing with a negative value for its size/weight. If an invalid painting is created you should
show an error.
Add at least one Sculpture object and one Painting object to your program and make calls to
superclass and subclass methods.
I want the program not to accept the negative value for the height and the width. But when I take the input it does not work i.e. it accepts the negative value
class Artwork2 {
String Artist;
int Value;
public Artwork2(String artist, int value) {
this.Artist=artist;
this.Value=value;
}
public int getValue() {
return this.Value;
}
public void setValue(int value) {
this.Value=value;
}
public String getArtist() {
return this.Artist;
}
public void setArtist(String artist) {
this.Artist=artist;
}
}
class Sculpture extends Artwork2 {
protected String material;
protected double weight;
public Sculpture(String artist, int value, String material, double weight) {
super(artist, value);
this.material=material;
this.weight=weight;
}
public String getMaterial() {
return this.material;
}
public void setMaterial(String material) {
this.material=material;
}
public double getWeight() {
return this.weight;
}
public void setWeight(double weight) {
this.weight=weight;
}
}
class Painting extends Artwork2 {
protected String paintType;
protected double canvasWidth;
protected double canvasHeight;
public Painting(String artist, int value,String paintType, double canvasWidth, double canvasHeight) {
super(artist, value);
this.paintType=paintType;
this.canvasHeight=canvasWidth;
this.canvasWidth=canvasHeight;
}
public double getCanvasWidth() {
return this.canvasWidth;
}
public void setCanvasWidth(double canvasWidth) {
this.canvasWidth=canvasWidth;
}
public double getCanvasHeight() {
return this.canvasHeight;
}
public void setCanvasHeight(double canvasHeight) {
if (canvasHeight < 0) {
throw new IllegalArgumentException();}
this.canvasHeight = canvasHeight;
}
public String getPaintType() {
return this.paintType;
}
public void setPaintType(String paintType) {
this.paintType=paintType;
}
}
public class SuperClass {
public static void main(String[] args) {
Sculpture sculpture= new Sculpture("lap", 1000,"top", 99);
System.out.println(sculpture.getArtist()+sculpture.getMaterial()+sculpture.getValue()+sculpture.getWeight());
Scanner in=new Scanner(System.in);
double canvas=in.nextDouble();
Painting painting =new Painting("lap", -1000,"oil", canvas, -10);
System.out.println(painting.getArtist()+
painting.getCanvasHeight()+painting.getCanvasWidth()+painting.getPaintType()+
painting.getValue());
}
}

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);
}
}

How do I calculate subTotal using one method and multiple constants and variables?

I'm just getting into java and have a program I need to write with a Class and ClassDriver. I'm supposed to write a program to calculate the total for cheesecake orders (four different kinds) based on price and count. The price given for each is constant. The count is based on user input. There can be only one subTotal method to calculate the subtotal of all the cheesecakes bought.
I'm not sure of the concept I need to do for this and I've been trying to do this for some hours now. Please help as soon as you are able to.
public class CheesecakeOrder {
private final double PLAIN_CHEESECAKE_PRICE=10.0;
private final double MARBLE_CHEESECAKE_PRICE=15.0;
private final double CHOCO_CHIP_CHEESECAKE_PRICE=18.0;
private final double VARIETY_CHEESECAKE_PRICE=22.0;
private final double SCHOOL_SHARE_RATE=.12;
private int plainCheesecakeCount=0;
private int marbleCheesecakeCount=0;
private int chocoChipCheesecakeCount=0;
private int varietyCheesecakeCount=0;
public double getPLAIN_CHEESECAKE_PRICE()
{
return PLAIN_CHEESECAKE_PRICE;
}
public double getMARBLE_CHEESECAKE_PRICE()
{
return MARBLE_CHEESECAKE_PRICE;
}
public double getCHOCO_CHIP_CHEESECAKE_PRICE()
{
return CHOCO_CHIP_CHEESECAKE_PRICE;
}
public double getVARIETY_CHEESECAKE_PRICE()
{
return VARIETY_CHEESECAKE_PRICE;
}
public int getPlainCheesecakeCount()
{
return plainCheesecakeCount;
}
public int getMarbleCheesecakeCount()
{
return marbleCheesecakeCount;
}
public int getChocoChipCheesecakeCount()
{
return chocoChipCheesecakeCount;
}
public int getVarietyCheesecakeCount()
{
return varietyCheesecakeCount;
}
public void setPlainCheesecake(int plainCheesecakeCount)
{
this.plainCheesecakeCount=plainCheesecakeCount;
}
public void setMarbleCheesecake(int marbleCheesecakeCount)
{
this.marbleCheesecakeCount=marbleCheesecakeCount;
}
public void setChocoChipCheesecakeCount(int chocoChipCheesecakeCount)
{
this.chocoChipCheesecakeCount=chocoChipCheesecakeCount;
}
public void setVarietyCheesecakeCount(int varietyCheesecakeCount)
{
this.varietyCheesecakeCount=varietyCheesecakeCount;
}
public double calculateSubTotal()
{
double subTotal;
subTotal = price * count;
return subTotal;
}
public double calculateDonation()
{
double donation;
donation = (calculateSubTotal()*SCHOOL_SHARE_RATE);
return donation;
}
public double calculateTotal()
{
double total;
total = donation+calculateSubTotal();
return total;
}
}
Try using a method that uses variable arguments as its parameter. Find the argument count from the passed variable, then loop through and calculate each one until you reach the end of the collection.

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).

Can't seem to return value

I just edited my post to update my code... I am still getting an error message when I compile stating that "Cannot find symbol". I have never seen this error so I am not sure how to debug it, I really appreciate everyone's help!
public class HealthRecord {
private int ID; // stores ID number
private String last; // stores last name
private String first; //stores first name
private double height; // stores height
private double weight; // stores weight
private double bmi;// i may need to create the bmi variable so that it can be stored (weight / (height*height)) *703;
public HealthRecord( int ID, String last, String first, double height, double weight)
{
this.ID = ID;
this.last = last;
this.first = first;
this.height = height;
this.weight = weight;
this.bmi = bmi;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public String getFirst() {
return first;
}
public void setFirst(String last) {
this.first = first;
}
public double getheight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public double getbmi() {
return (weight / (height*height)) *703;
}
public void setbmi(double bmi) {
this.bmi = bmi;
}
}
Next Class
import java.util.Scanner;
import java.io.File;
public class OpenFile
{
private Scanner input;
public void openFile() throws Exception
{
input = new Scanner(new File("medrec.txt")); // opens the text file to be read (weight / (height*height)) *703);
}
public void readFile()
{
int ID; // stores ID number
String last; // stores last name
String first; //stores first name
double height; // stores height
double weight; // stores weight
input.nextLine();
while(input.hasNextLine())
{
ID = input.nextInt();
last = input.next();
first = input.next();
height = input.nextDouble();
weight = input.nextDouble();
HealthRecord healthrecord= new HealthRecord(ID,last,first,height,weight);
System.out.printf("%d", healthrecord.getID(), healthrecord.getBmi());
}
}
public void closeFile()
{
input.close();
}
}
Replace
System.out.printf("%d %d", HealthRecord.getID, HealthRecord.getBmi);
with
System.out.printf("%d %f", healthrecord.getID(), healthrecord.bmi());
Use the healthrecord instance that you created. The method getID requires parenthesis. Also getBmi doesn't exist as a method. Currently you have bmi.
Aside:
Currently this code doesn't compile. All methods in openFile are instance methods. You need to create an instance and use:
Openfile myOpenfile = new Openfile();
myOpenfile.openFile();
myOpenfile.readFile();
myOpenfile.closeFile();
Java naming conventions indicate class names start with uppercase letters, e.g. Openfile
Edit:
In your updated file, getBmi does not exist but rather getbmi:
System.out.printf("%d %f", healthrecord.getID(), healthrecord.getbmi());
^
You may want to rename the method to getBmi to follow method naming conventions.
I don't see any bmi calculation in HealthRecord constructor or in getter method of bmi.
Even I don't see getBmi() method in HealthRecord class.
Add below method in HealthRecord class :
public double getBmi() {
return (weight / (height*height)) *703; //check this formula if it is correct for BMI calculation or not
}
And next you need to use this call in main class:
System.out.printf("%d %d", healthrecord.getID(), healthrecord.getBmi());

Categories