Hr r ett exempel
Kod:
import java.util.Scanner;
public class HiLo {
public static void main(String[] args) {
System.out.println("Welcome to HiLo!");
System.out.println("Difficulty");
System.out.println("1. Easy (1-10)");
System.out.println("2. Medium (1-100)");
System.out.println("3. Hard (1-1000)");
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
if (choice == 1) {
playGame(10);
} else if (choice == 2) {
playGame(100);
} else if (choice == 3) {
playGame(1000);
}
}
public static void playGame(int maxNumber) {
Scanner sc = new Scanner(System.in);
int number = (int) (Math.random() * maxNumber) + 1;
System.out.println("Guess a number between 1 - " + maxNumber);
int guess = 0;
int attempts = 0;
while (guess != number) {
guess = sc.nextInt();
giveResponse(guess, number, attempts++);
}
}
public static void giveResponse(int guess, int answer, int attempts) {
if (guess == answer) {
System.out.println("GOOD WORK.");
System.out.println("You guessed correct in [" + attempts + "] attempts");
return;
}
if (guess < answer) {
System.out.println("Too low, try again!");
} else {
System.out.println("Too high, try again!");
}
}
}