Menu

[Solved]Suppose Want Program Lets Users Select Games Play Game Class Standard Tostring Method Desc Q37274065

  • Suppose you want to have a program that lets users select gamesto play, where each game is in a class that has a standard toStringmethod describing itself, and a play method, with no parameters,that returns an int final score for the game. Write an interfacecalled Game.java for this.

    Below is a simple program that could use Game1, Game2 and Game3classes satisfying the interface, and using my UI class. For theprogram below to be consistent with the next problem, we assumeGame1 has a constructor with one int parameter:

    public class PlayGames { public static void main(String[] args) { Game[] games = {new Game1(3), new Game2(), new Game3()}; int nGames = games.length; int cumulativeScore = 0; String[] prompts = new String[nGames+1]; prompts[0] = “0: Quit”; for (int i = 0; i < nGames; i++) { // use toString methods prompts[i+1] = String.format(“%s: %s”, i+1, games[i]); } int n; do { for (String prompt: prompts) { System.out.println(prompt); } n = UI.promptInt(“Game number: “); if (n != 0) { cumulativeScore += games[n-1].play(); System.out.println(“Your cumulative score is now: ” + cumulativeScore); } } while (n != 0); System.out.println(“Thanks for playing!”); }}

  • What is wrong with this attempt at a Game1 class for part a,that has to do with interfaces (not just being boring)?

    import java.util.Random;public class Game1 { private Random rand; private int nTry; public Game1(int tries) { nTry = tries; rand = new Random(); } public int play() { int score = 0; for (int i = 0; i < nTry; i++) { int x = rand.nextInt(100); int y = rand.nextInt(100); int ans = UI.promptInt(x + ” + ” + y + “= “); if (ans == x + y) { score++; System.out.println(“Correct!”); } else { System.out.println(“No, the answer is ” + (x+y)); } } return score; } public String toString() { return “Do ” + nTry + ” small arithmetic sums.”; }}

    If you want to test all of this together, without creating Game2and Game3, you could replace new Game2(), new Game3() in theinitialization of games by new Game1(2), new Game1(4). This justmakes even more boring games. A further extension (not required)would be to make more quite different games to include in theinitialization of games.

Expert Answer


Answer to Suppose you want to have a program that lets users select games to play, where each game is in a class that has a stand… . . .

OR


Leave a Reply

Your email address will not be published. Required fields are marked *