This commit is contained in:
Luca Conte 2022-11-24 18:04:55 +01:00
parent b06ede766f
commit 6c6523afd2
2 changed files with 56 additions and 0 deletions

Binary file not shown.

View File

@ -0,0 +1,56 @@
import java.util.Scanner;
import java.util.Random;
/**
* Klasse zum Erraten einer Zahl
*/
public class ZahlenRaten {
public static void main(String[] args) {
System.out.println("Denken Sie sich eine Zahl zwischen 1 und 10 aus.");
System.out.println("Ich werde versuchen, diese zu erraten.\n");
Random random = new Random();
Scanner console = new Scanner(System.in);
int versuche = 1;
int guess = random.nextInt(10) + 1;
while (!fragen(console, guess)) {
guess = random.nextInt(10) + 1;
versuche++;
}
System.out.println("\nIch habe " + versuche + " Versuche gebraucht.");
}
/**
* Fragt den Benutzer ob eine Zahl die richtige ist
* Falls ja, wird true zurueckgegeben, andernfalls false
* Fragt so lange nach, bis eine gueltige Antwort gegeben wird
*/
public static boolean fragen(Scanner console, int zahl) {
String input = einmalFragen(console, zahl);
while (true) {
if (input.equals("J")) {
return true;
}
if (input.equals("N")) {
return false;
}
System.out.println("Bitte antworten Sie mit J oder N.");
input = einmalFragen(console, zahl);
}
}
/**
* Fragt den Benutzer ob eine Zahl die richtige ist
* Gibt die Eingabe des Benutzers in Grossbuchstaben zurueck
*/
public static String einmalFragen(Scanner console, int zahl) {
System.out.print("Ist es die " + zahl + "? (J/N) ");
String input = console.nextLine().toUpperCase();
return input;
}
}