Here's a simple Java program to simulate a game of cricket:
import java.util.Random;
import java.util.Scanner;
class CricketGame {
private int overs;
private int runs;
private int wickets;
private String teamName;
public CricketGame(String teamName, int overs) {
this.teamName = teamName;
this.overs = overs;
this.runs = 0;
this.wickets = 0;
}
public void playGame() {
Random random = new Random();
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < overs; i++) {
System.out.println("Over " + (i + 1));
for (int j = 0; j < 6; j++) {
System.out.print("Ball " + (j + 1) + ": ");
String input = scanner.nextLine();
int runsScored = random.nextInt(7); // 0-6 runs
if (input.equalsIgnoreCase("wicket")) {
wickets++;
System.out.println("Wicket fallen!");
} else {
runs += runsScored;
System.out.println(runsScored + " runs scored.");
}
}
}
System.out.println("\nGame over!");
System.out.println(teamName + " scored " + runs + " runs with " + wickets + " wickets.");
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter team name: ");
String teamName = scanner.nextLine();
System.out.print("Enter number of overs: ");
int overs = scanner.nextInt();
CricketGame game = new CricketGame(teamName, overs);
game.playGame();
}
}
This program simulates a game of cricket where the user inputs the team name and number of overs. The game is played over the specified number of overs, with each over consisting of six balls. The user can input "wicket" to simulate a wicket, and the program generates a random number of runs (0-6) for each ball. The game ends after the specified number of overs, and the final score is displayed.
No comments:
Post a Comment