Home > Net >  How can I add an error statement in a loop if the user entered letters instead of numbers but the pr
How can I add an error statement in a loop if the user entered letters instead of numbers but the pr

Time:10-30

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! :)))

CodePudding user response:

You can check for errors using try and catch blocks. All you have to do is wrap the error-prone code in a try block and check for a SPECIFIC exception and handle it. Don't just leave the catch empty, it is a bad practice. You could do it this way, but I would recommend using if statements to check if your input contains numbers

CodePudding user response:

Scanner scan = new Scanner(System.in);
        Random rand = new Random();
        int playerGuess=0;
        int randomNum = rand.nextInt(50)   1;
        int numberOfAttempts = 0;
        while (true) {
            System.out.println("Guess a number from 1 to 50: ");

            try {
                playerGuess = scan.nextInt();
                numberOfAttempts  ;
            } catch (Exception ex) {
                System.out.println("Please enter only number!");
                scan=new Scanner(System.in);
            }

            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.");
            }
        }
  • Related