JAVA-5
Q.5 Write a java program to create a player history that can be display in the following form.
Player name and team name is stored in Player class. Score of test match and One Day match in the
other class say Run class number of One Day match and number of test match must be in Match class
and finally calculate the average. The package1 contains Player,Run and Match classes, Where
package2 contain main() class.
Solution :-Â
// Package 1: package1 (Player, Run, Match classes)
package package1;
// Player class
public class Player {
protected String playerName;
protected String teamName;
public Player(String playerName, String teamName) {
this.playerName = playerName;
this.teamName = teamName;
}
}
// Run class
class Run {
protected int testMatchRuns;
protected int oneDayRuns;
public Run(int testMatchRuns, int oneDayRuns) {
this.testMatchRuns = testMatchRuns;
this.oneDayRuns = oneDayRuns;
}
}
// Match class
class Match {
private int testMatches;
private int oneDayMatches;
private Run run;
public Match(int testMatches, int oneDayMatches, int testMatchRuns, int oneDayRuns) {
this.testMatches = testMatches;
this.oneDayMatches = oneDayMatches;
this.run = new Run(testMatchRuns, oneDayRuns);
}
public double calculateAverage() {
int totalMatches = testMatches + oneDayMatches;
int totalRuns = run.testMatchRuns + run.oneDayRuns;
return totalMatches == 0 ? 0 : (double) totalRuns / totalMatches;
}
public void display(Player player) {
System.out.println("Player Name: " + player.playerName);
System.out.println("Team Name: " + player.teamName);
System.out.println("Test Match Runs: " + run.testMatchRuns);
System.out.println("One Day Match Runs: " + run.oneDayRuns);
System.out.println("Test Matches: " + testMatches);
System.out.println("One Day Matches: " + oneDayMatches);
System.out.println("Average Score: " + calculateAverage());
}
}
// Package 2: package2 (MainClass)
package package2;
import package1.*;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Player Name: ");
String playerName = scanner.nextLine();
System.out.print("Enter Team Name: ");
String teamName = scanner.nextLine();
System.out.print("Enter Test Matches Played: ");
int testMatches = scanner.nextInt();
System.out.print("Enter One Day Matches Played: ");
int oneDayMatches = scanner.nextInt();
System.out.print("Enter Test Match Runs: ");
int testMatchRuns = scanner.nextInt();
System.out.print("Enter One Day Match Runs: ");
int oneDayRuns = scanner.nextInt();
Player player = new Player(playerName, teamName);
Match match = new Match(testMatches, oneDayMatches, testMatchRuns, oneDayRuns);
System.out.println("\nPlayer History:");
match.display(player);
scanner.close();
}
}