Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the Hero object class below. There are 10 syntax or logic errors or poo

ID: 3575055 • Letter: C

Question

Consider the Hero object class below. There are 10 syntax or logic errors or poor programming practices. Ide show how they would be corrected. public class Hero {public int health; private String name; public void Hero () {health = 100; string name = "Brave Sir Robin !";} public Hero (String name) {health = 100; name = name;}//Accessors not required since there is a toString method. They do the same public int attack () {return (int) (Math.random *10);} public int takeDamage (int d) {health - = d;} public static boolean isAlive {if (health > 0) return true;} public void toString () {System. out.println ("Hero {" + ", " + health + "] ");}}

Explanation / Answer

public class Hero{

//public int health; // poor practice scenario of class variable being public should have get method to get health.
private int health; // fixed code for above line
private String name;

//public void Hero(){ //incorrect constructor with return type void
public Hero(){ // fixed code for above line
health=100;
//String name="Brave Sir Robin!"; //incorrect initializes the local name variable not class variable
name="Brave Sir Robin!"; // fixed code for above line
}

public Hero(String name){
health=100;
//name=name; //incorrect assignment as argument and class variable are same;
this.name=name; //incorrect assignment as argument and class variable are same;
}

// Accessors not required since there is toString method. They do the same.

// Above statement is incorrect, all requried class variable should have get or set method accordingly.

   public int getHealth() { return health; } //fixed code

public int attack() { return (int)(Math.random()*10); }

//public int takeDamage(int d) { health-=d; } // no return statement for damage;
public int takeDamage(int d) { health-=d; return health; } // returns health after attack;

//public static boolean isAlive{ // static method refering non-static class variable and no braces in method name
public boolean isAlive() { // fixed code for above line
//if(health > 0) return true; } // there is no handling of false scenario which is incorrect.
return (health > 0); } //fixed code for above line return true or false based on health being +ve

//public void toString(){ // toString override should actually return string rather being void function
public String toString(){ //fixed code for above line
//System.out.println("Hero[" + name + "," + health + "]"); } // not valid to do System.out better return String
return "Hero[" + name + "," + health + "]"; }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote