package simplegame; import java.util.Random; import java.util.Scanner; /** * Part of the second exercise. * Simple example game with a (volatile) highscore table. * This file only contains an incomplete template. * Please add the mandatory code in the following methods: * - showHighscore * - insertScore */ public class HiLoGame { /** * Array to store highscore information. * highscore[0] = top score * highscore[9] = lowest highscore */ private static int[] highscore = new int[10]; /** * Runs through the array in a for loop and prints the scores. * The top score should be printed first. */ public static void showHighscore() { System.out.println("*** HIGHSCORE ***"); // TODO: Add code here } /** * Enters a new score into the highscore array. * The order must be maintained and no lower score should ever replace a higher one. */ public static void insertScore(int score) { // TODO: Add code here // Some ideas but you may achieve the goal completely different: // At first check if the score is good enough for entering the // highscore list. Second use a while loop or something similar // to determine where the new score needs to be put. Third a for // loop to shift every score lower than the new score in the array. } /** * Should show a valid highscore table. * Especially the values must always appear in descending order. */ public static void testScore() { for (int i=0; i<100; i+=10) insertScore(i); insertScore(55); showHighscore(); insertScore(15); showHighscore(); insertScore(95); showHighscore(); insertScore(5); showHighscore(); } /** * The game :-). */ public static void main(String[] args) { boolean done = false; Random rand = new Random(); Scanner sc= new Scanner(System.in); System.out.println("Welcome to HiLo, I've got a secret number between 0 and 99 ..."); while (!done) { int step = 0; int secret = rand.nextInt(100); int guess = 0; do { System.out.print("Guess: "); guess = sc.nextInt(); if (guess < secret) System.out.println("too low, guess higher"); if (guess > secret) System.out.println("too high, guess lower"); ++step; } while (secret != guess); int score = (31 - step) * 7 + rand.nextInt(7); if (score < 0) score = 0; System.out.println("Congratulation, your score is: "+score); insertScore(score); showHighscore(); System.out.println("Play again? (Yes/No) "); String str = sc.next(); done = str.contains("N") || str.contains("n"); } System.out.println("Bye bye"); } }