SHOW:
|
|
- or go back to the newest paste.
1 | import java.util.Scanner; | |
2 | ||
3 | ||
4 | public class Testcode { | |
5 | public static void main(String[] args){ | |
6 | ||
7 | Scanner input = new Scanner(System.in); | |
8 | boolean playAgain = false; | |
9 | do{ | |
10 | System.out.println("Guess the random number:"); | |
11 | ||
12 | int userGuess = -1; | |
13 | int randomNumber = 5; | |
14 | int numberOfAttempts = 1; | |
15 | ||
16 | String text = input.nextLine(); | |
17 | userGuess = checkIfInteger(text, input); //keeps asking for a integer until it has one. | |
18 | ||
19 | while(userGuess != randomNumber){ | |
20 | System.out.println("You guessed wrong! Guess again:"); | |
21 | text = input.nextLine(); | |
22 | userGuess = checkIfInteger(text, input); | |
23 | numberOfAttempts++; | |
24 | } | |
25 | ||
26 | if(userGuess == randomNumber){ | |
27 | System.out.println("You guessed right in "+numberOfAttempts+" attempts."); | |
28 | System.out.println("Wanna play again?"); | |
29 | String reply = input.nextLine(); | |
30 | ||
31 | if(reply.toLowerCase().startsWith("y")){ | |
32 | playAgain = true; | |
33 | } | |
34 | else{ | |
35 | playAgain = false; | |
36 | } | |
37 | ||
38 | } | |
39 | } while (playAgain); | |
40 | } | |
41 | ||
42 | private static int checkIfInteger(String text, Scanner input) { | |
43 | while(true){ | |
44 | try{ | |
45 | int number = Integer.parseInt(text); | |
46 | return number; | |
47 | } | |
48 | catch(NumberFormatException nfe){ | |
49 | System.out.println("You didnt write an integer! Please try again:"); | |
50 | text = input.nextLine(); | |
51 | } | |
52 | } | |
53 | } | |
54 | } |