Java Program printing infinitely before crashing - java

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

Related

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

can i print a setter value (sysout) or do i have to use only getters in order to get an output ? (java)

I have just recently learned about setter , getters and this.(somthing).
I having quite a hard time undersatnding when to use getters and when to use setters .
Another thing , can i use setter method to print out ?
For Example :
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
newAge = workerAge;
}
public void setWorkerName(String newName) {
newName = workerName;
}
public int setIde(int ide) {
ide = workerIde;
return ide;
}
}
public class App {
public static void main(String[] args) {
workerId worker1 = new workerId();
worker1.setWorkerAge(41);
worker1.setWorkerName("dan ");
worker1.setIde(318574524);
System.out.println(worker1.setIde());
}
}
the system out print shows an error and i didnt understand why , is it because only getters can be used in the sysout command ?
No offense intended, but your setters are all wrong. You should assign your properties to the values passed in the setter, not setting the value again. So your code should look like this:
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
workerAge = newAge;
}
public void setWorkerName(String newName) {
workerName = newName;
}
public int setIde(int ide) {
workerIde = ide;
}
}
If you need getters, it should look like this:
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
workerAge = newAge;
}
public void setWorkerName(String newName) {
workerName = newName;
}
public int setIde(int ide) {
workerIde = ide;
}
public int getIde() {
return workerIde;
}
}
Then you can print, e.g. System.out.println(worker1.getIde());
You should be using a getter method to get the values.
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
workerAge = newAge;
}
public void setWorkerName(String newName) {
workerName=newName;
}
public int getIde() {
return workerIde;
}
public void setIde(int ide) {
workerIde = ide;
}
}
public class App {
public static void main(String[] args) {
workerId worker1 = new workerId();
worker1.setWorkerAge(41);
worker1.setWorkerName("dan ");
worker1.setIde(318574524);
System.out.println(worker1.getIde());
}
}
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
this.workerAge = newAge;
}
public void setWorkerName(String newName) {
this.workerName = newName;
}
public int setIde(int ide) {
this.workerIde = ide;
return this.workerIde;
}
}
public class Car {
public static void main(String[] args) {
workerId worker1 = new workerId();
worker1.setWorkerAge(41);
worker1.setWorkerName("dan ");
worker1.setIde(318574524);
System.out.println(worker1.setIde(56));
}
}

OOP the other method if is not working why?

I do not know why the if statement is not working in the program.
When order is greater than bulkorder, it still returns 0.
Do you think there is a problem with the code I have written which is shown below?
public class ShoeStoreOrder{ //ShoeStoreOrder .java
// private method
private String typeofshoe ;
private String season ;
private double cost ;
private int bulkOrderQuantity;
private int discount;
private int order;
//constructor
public ShoeStoreOrder(String t,String s,double c,int b,int d,int o){
typeofshoe = t;
season = s;
cost = c;
bulkOrderQuantity = b;
discount = d;
order = o;
}
//get Method
public String gettypeofshoe(){
return typeofshoe;
}
public String getseason(){
return season;
}
public double getcost(){
return cost;
}
public int getbulkOrderQuantity(){
return bulkOrderQuantity;
}
public int getdiscount(){
return discount;
}
public int getorder(){
return order;
}
//set method
public void settypeofshoe(String t){
typeofshoe=t;
}
public void setseason(String s){
season=s;
}
public void setcost(double c){
cost=c;
}
public void setbulkOrderQuantity(int b){
bulkOrderQuantity=b;
}
public void setorder(int o){
order=o;
}
//other method
//overload method
public double gettotaldiscount(){
if(order()>bulkOrderQuantity()){
return order*cost*(discount/100);
}
else{
return 0;
}
}
public double gettotalamount(){
return order*cost-gettotaldiscount();
}
}
order and bulkOrderQuantity are instance variable and not a method. () are used when calling a method and not when referencing a variable:
if(order()>bulkOrderQuantity()){
change it to
if(order>bulkOrderQuantity){
You have skipped case when order value equals bulkOrderQuantity:
public double gettotaldiscount() {
if (order >= bulkOrderQuantity) {
return order * cost * discount / 100;
} else {
return 0;
}
}
//Check input and results:
public static void main(String[] args) {
ShoeStoreOrder sso;
System.out.println("No discount");
sso = new ShoeStoreOrder("vertical", "winter", 20, 5, 10, 1);
System.out.println(sso.gettotalamount());
System.out.println("After discount");
sso = new ShoeStoreOrder("vertical", "winter", 20, 5, 10, 5);
System.out.println(sso.gettotalamount());
sso = new ShoeStoreOrder("vertical", "winter", 20, 5, 10, 50);
System.out.println(sso.gettotalamount());
}
Output:
No discount
20.0
After discount
90.0
900.0

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;

Sorting values with Comparator changes all the values with that object

I am working in an android application I want to sort a List of Objects with an Object Property. I have sorted it successfully but when I sort it all the List with that object changes the value to same as the sorted value
Please look into ma code :
SortedSet<Caseload> removeDuplicateClientName = new TreeSet<Caseload>(
new Comparator<Caseload>() {
#Override
public int compare(Caseload caseload0, Caseload caseload1) {
return caseload0.ClientName.compareTo(caseload1.ClientName);
}
});
// Getting the list of values from web service
mLISTCaseloadsHeads = parsedXML.getCaseLoadValues("get_Caseload_ClientServiceGroupID", param);
List<Caseload> newBackUp=mLISTCaseloadsHeads ;
Iterator<Caseload> iterator = mCaseloadsHeads.iterator();
while (iterator.hasNext()) {
removeDuplicateClientName.add(iterator.next());
}
mCaseloadsHeads.clear();
mCaseloadsHeads.addAll(removeDuplicateClientName);
The List newBackUp also changes the value to the same as sorted List
Caseload class:
public class Caseload implements Comparable<Caseload> {
public int BusClientLogID;
public int ClientID;
public int ClientStatus;
public int ClientServiceGroup_ClientSiteTherapyID;
public String ClientName;
public String TimeArrive;
public String TimeDepart;
public String SignOutTime;
public String SignInTime;
public String ServiceCompletedCount;
public Boolean ShowFooter = false;
public int getBusClientLogID() {
return BusClientLogID;
}
public void setBusClientLogID(int busClientLogID) {
BusClientLogID = busClientLogID;
}
public int getClientID() {
return ClientID;
}
public void setClientID(int clientID) {
ClientID = clientID;
}
public int getClientStatus() {
return ClientStatus;
}
public void setClientStatus(int clientStatus) {
ClientStatus = clientStatus;
}
public int getClientServiceGroup_ClientSiteTherapyID() {
return ClientServiceGroup_ClientSiteTherapyID;
}
public void setClientServiceGroup_ClientSiteTherapyID(
int clientServiceGroup_ClientSiteTherapyID) {
ClientServiceGroup_ClientSiteTherapyID = clientServiceGroup_ClientSiteTherapyID;
}
public String getClientName() {
return ClientName;
}
public void setClientName(String clientName) {
ClientName = clientName;
}
public String getTimeArrive() {
return TimeArrive;
}
public void setTimeArrive(String timeArrive) {
TimeArrive = timeArrive;
}
public String getTimeDepart() {
return TimeDepart;
}
public void setTimeDepart(String timeDepart) {
TimeDepart = timeDepart;
}
public String getSignOutTime() {
return SignOutTime;
}
public void setSignOutTime(String signOutTime) {
SignOutTime = signOutTime;
}
public String getSignInTime() {
return SignInTime;
}
public void setSignInTime(String signInTime) {
SignInTime = signInTime;
}
public String getServiceCompletedCount() {
return ServiceCompletedCount;
}
public void setServiceCompletedCount(String serviceCompletedCount) {
ServiceCompletedCount = serviceCompletedCount;
}
#Override
public int compareTo(Caseload compareCaseload) {
int busClientLogID = ((Caseload) compareCaseload).getBusClientLogID();
return busClientLogID - this.BusClientLogID;
}
}
Please give me a solution.
I doubt the return statement associated with your compare function in the comparator.
You should go by this approach to get the right ordering :
#Override
public int compare(YourClass lhs, YourClass rhs) {
YourClass p1 = (YourClass) lhs;
YourClass p2 = (YourClass) rhs;
int first = p1.ClientName; //use your getter if you want
int second = p2.ClientName;
if (second < first) {
return 1;
}
else if (second > first) {
return -1;
}
else {
return 0;
}
}
If you go by this approach I guess you will get the required ordering after sort.
Edit:
Now I have got the issue, you are using a reference of the original list in newBackup and its not a new list that is why this is happening, use this and you are good to go.
List<Caseload> newBackUp=new ArrayList<Caseload>(mLISTCaseloadsHeads);

Categories