vendredi 29 octobre 2021

How can I add an error statement in a loop if the user entered letters instead of numbers but the program should continue

package sample;

import java.util.Scanner; import java.util.Random;

public class Main {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    Random rand = new Random();
    int playerGuess;
    int randomNum = rand.nextInt(50) + 1;
    int numberOfAttempts = 0;
    while (true) {
        System.out.println("Guess a number from 1 to 50: ");
        playerGuess = scan.nextInt();
        numberOfAttempts++;

        if (playerGuess == randomNum) {
            System.out.println("Congratulations! The number was: " + randomNum);
            System.out.println("You got it in " + numberOfAttempts + " attempts.");
            break;
        }
        else if (randomNum > playerGuess) {
            System.out.println("Your guess is too low. Try again.");
        }
        else {
            System.out.println("Your guess is too high. Try again.");
        }
    }
}

}My program works fine but I forgot how to add an error statement in a loop. Can someone help me where and how to add an error statement when the user entered letters instead of numbers. Thank you in advance! :)))




Aucun commentaire:

Enregistrer un commentaire