This article describes the Java implementation of the simple guessing game code. Share to everyone for your reference.
The specific code is as follows:
Copy Code code as follows:
Import java.util.InputMismatchException;
Import Java.util.Scanner;
public class Main {
public static void Main (string[] args) {
produce a random number
int number = (int) (Math.random () * 100) + 1;
Add Count
int count = 0;
Add the maximum value here and the minimum value
int max = 100;
int min = 1;
while (true) {
Keyboard input data
Scanner sc = new Scanner (system.in);
SYSTEM.OUT.PRINTLN ("Please input the data you want to guess: (" + min + "~" + Max + ")");
try {
count++;
int guessnumber = Sc.nextint ();
Judge
if (Guessnumber > number) {
max = Guessnumber;
System.out.println ("You guessed big");
else if (Guessnumber < number) {
min = Guessnumber;
System.out.println ("You guessed small");
} else {
System.out.println ("Congratulations, spent" + Count + "the second guessed");
Ask whether to continue
System.out.println ("Would you like to continue?") (yes) ");
sc = new Scanner (system.in);
String str = sc.nextline ();
if ("Yes". Equals (str)) {
Override assignment Random number
Number = (int) (Math.random () * 100) + 1;
Count = 0;
max = 100;
min = 1;
} else {
Break
}
}
catch (Inputmismatchexception e) {
SYSTEM.OUT.PRINTLN ("The data you entered is incorrect");
}
}
}
}
The results of the operation are shown in the following illustration:
I hope this article will help you with your Java programming.