Define a Class called Ninja. a. Make instance variables for name, dojoName, and
ID: 3839967 • Letter: D
Question
Define a Class called Ninja. a. Make instance variables for name, dojoName, and killCount. b. Create a static variable for totalKills c. Create a default constructor that defaults name to "No Name yet", dojoName to "No Name yet" and killCount to 0. d. Create a constructor that has parameters that set the value for name and dojo name. This will also set killCount to 0. Create accessor methods for all the variables (name, dojoName, killCount and totalKills). e. Create a method that increments killCount and totalKills f. Create a STATIC method that compares 2 ninjas to see who has more kills. This method will print out the name of the ninja with more kills and what percentage his kill number is from the total kills.Explanation / Answer
Ninja.java
import java.text.DecimalFormat;
public class Ninja {
//Declaring instance variables
private String name;
private String doName;
private int killCount=0;
static int totalKills=0;
//Zero argumented constructor
public Ninja() {
this.name = "No Name yet";
this.doName = "No Name yet";
this.killCount = 0;
}
//Parameterized constructor
public Ninja(String name, String doName) {
this.name = name;
this.doName = doName;
this.killCount = 0;
}
//getters
public String getName() {
return name;
}
public String getDoName() {
return doName;
}
public int getKillCount() {
return killCount;
}
public static int getTotalKills() {
return totalKills;
}
//This method will increment kill count and total kill count
void inKillCount()
{
killCount++;
totalKills++;
}
//this method compare the two ninja's kill count and display percentage of kills
static void compareNinjas(Ninja n1,Ninja n2)
{
double perc;
DecimalFormat df=new DecimalFormat("#.##");
if(n1.getKillCount()>n2.getKillCount())
{
perc=((double)n1.getKillCount()/n1.getTotalKills())*100;
System.out.println(n1.getName()+" Killed more with percentage "+df.format(perc)+"%");
}
else
{
perc=((double)n2.getKillCount()/n2.getTotalKills())*100;
System.out.println(n2.getName()+" Killed more with percentage "+df.format(perc)+"%");
}
}
}
________________________
TestNinja.java
public class TestNinja {
public static void main(String[] args) {
//Creating an object to Ninja class
Ninja n1=new Ninja("Ken","Akara");
n1.inKillCount();
n1.inKillCount();
n1.inKillCount();
n1.inKillCount();
n1.inKillCount();
n1.inKillCount();
//Creating an object to Ninja class
Ninja n2=new Ninja("Hung","Dojang");
n2.inKillCount();
n2.inKillCount();
n2.inKillCount();
n2.inKillCount();
//Comparing two ninja class objects
Ninja.compareNinjas(n1, n2);
}
}
__________________
Output:
Ken Killed more with percentage 60%
__________________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.