Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Testcode {
- public static void main(String[] args){
- Scanner input = new Scanner(System.in);
- boolean playAgain = false;
- do{
- System.out.println("Guess the random number:");
- int userGuess = -1;
- int randomNumber = 5;
- int numberOfAttempts = 1;
- String text = input.nextLine();
- userGuess = checkIfInteger(text, input); //keeps asking for a integer until it has one.
- while(userGuess != randomNumber){
- System.out.println("You guessed wrong! Guess again:");
- text = input.nextLine();
- userGuess = checkIfInteger(text, input);
- numberOfAttempts++;
- }
- if(userGuess == randomNumber){
- System.out.println("You guessed right in "+numberOfAttempts+" attempts.");
- System.out.println("Wanna play again?");
- String reply = input.nextLine();
- if(reply.toLowerCase().startsWith("y")){
- playAgain = true;
- }
- else{
- playAgain = false;
- }
- }
- } while (playAgain);
- }
- private static int checkIfInteger(String text, Scanner input) {
- while(true){
- try{
- int number = Integer.parseInt(text);
- return number;
- }
- catch(NumberFormatException nfe){
- System.out.println("You didnt write an integer! Please try again:");
- text = input.nextLine();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement