Code a class named Target that keeps track of the name (as a String), the score
ID: 3635763 • Letter: C
Question
Code a class named Target that keeps track of the name (as a String), the score (as an int), originally 0, and the number of shots (as an int), originally 0, of a player shooting at a target. The constructor accepts the name of the player as a parameter. Shots can either hit red (modeled by a method named red) which doubles the current score or adds 5 points to the score, whichever is better, hit blue (modeled by a method named blue) which scores 10 points, hit white (modeled by a method named white) which scores 4 points, or miss (modeled by a method named miss) which loses 3 points. A toString method will return a string indicating the current player, number of shots taken, and scoreExplanation / Answer
//Program 1: Target .java public class Target { private String name; private int score; private int noOfShots; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNoOfShots() { return noOfShots; } public void setNoOfShots(int noOfShots) { this.noOfShots = noOfShots; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public Target(String name) { super(); this.name = name; this.score=0; this.noOfShots=0; } public void hitRed(){ this.score +=5; this.noOfShots +=1; } public void hitBlue(){ this.score +=10; this.noOfShots +=1; } public void hitWhite(){ this.score +=4; this.noOfShots +=1; } public void miss(){ this.score -=3; this.noOfShots +=1; } public String toString(){ StringBuffer sb= new StringBuffer(); sb.append("Current Player: ").append(this.name).append(" "); sb.append("Number of shots taken: ").append(this.noOfShots).append(" "); sb.append("Score: ").append(this.score).append(" "); return sb.toString(); } public void hitTarget(int index){ switch (index) { case 0: miss(); break; case 1: hitRed(); break; case 2: hitBlue(); break; case 3: hitWhite(); break; default: miss(); break; } } } //Program 2: TestTarget.java import java.util.Random; import java.util.Scanner; public class TestTarget { public static void main(String[] args) { String f = "n"; Random rand = new Random(); Scanner scan = new Scanner(System.in); System.out.println("Enter Player Name::.."); String name = scan.nextLine(); Target target = new Target(name); System.out.println(target.toString()); target.hitBlue(); System.out.println(target.toString()); target.hitRed(); System.out.println(target.toString()); target.hitWhite(); System.out.println(target.toString()); target.miss(); System.out.println(target.toString()); do{ System.out.println("Enter F to FIRE.."); f = scan.nextLine(); target.hitTarget(rand.nextInt(4)); }while(f.equals("f")); System.out.println(target.toString()); } }