Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible exception if User enters String instead of Int

I am just playing with Java.I'm trying to force my program to only accept 3 digit numbers. I believe I have successfully done this using a while loop (please correct me if I'm wrong). But how do I go about printing an error statement if the user enters a string. eg: "abc".

My code:

    import java.util.Scanner;
    public class DigitSum {

    public static void main(String[] args) {

    Scanner newScan = new Scanner(System.in);

        System.out.println("Enter a 3 digit number: ");
        int digit = newScan.nextInt();

        while(digit > 1000 || digit < 100)
            {           
             System.out.println("Error! Please enter a 3 digit number: ");
             digit = newScan.nextInt();
            }

        System.out.println(digit);
       }
    }
like image 918
binary101 Avatar asked Dec 18 '25 00:12

binary101


2 Answers

How about this?

public class Sample {
    public static void main (String[] args) {
        Scanner newScan = new Scanner (System.in);

        System.out.println ("Enter a 3 digit number: ");
        String line = newScan.nextLine ();
        int digit;
        while (true) {
            if (line.length () == 3) {
                try {
                    digit = Integer.parseInt (line);
                    break;
                }
                catch (NumberFormatException e) {
                    // do nothing.
                }
            }

            System.out.println ("Error!(" + line + ") Please enter a 3 digit number: ");
            line = newScan.nextLine ();
        }

        System.out.println (digit);
    }
}

regexp version:

public class Sample {
    public static void main (String[] args) {
        Scanner newScan = new Scanner (System.in);

        System.out.println ("Enter a 3 digit number: ");
        String line = newScan.nextLine ();
        int digit;

        while (true) {
            if (Pattern.matches ("\\d{3}+", line)) {
                digit = Integer.parseInt (line);
                break;
            }

            System.out.println ("Error!(" + line + ") Please enter a 3 digit number: ");
            line = newScan.nextLine ();
        }

        System.out.println (digit);
    }
}
like image 103
Ruzia Avatar answered Dec 20 '25 18:12

Ruzia


Embed the code for Reading the int in try catch block it will generate an exception whenever wrong input is entered then display whatever message you want in catch block

like image 27
Software Sainath Avatar answered Dec 20 '25 16:12

Software Sainath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!