2

How to have a try and catch statement to validate the input in variable odd is a number else print an error message? I am new in java programming. Appreciate any help

import java.util.Scanner;

public class ScenarioB{
    public static void main (String[]args){
        int odd;
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter An Odd Number\n");
        odd = scan.nextInt();
    }
}
Olli
  • 658
  • 5
  • 26
323 Kobby
  • 93
  • 2
  • 7
  • Possible duplicate of [How to check if a String is numeric in Java](https://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-java) – rghome Mar 13 '19 at 10:40
  • Or also: [How to check the input is an integer or not in Java? [duplicate] ](https://stackoverflow.com/questions/19925047/how-to-check-the-input-is-an-integer-or-not-in-java) – rghome Mar 13 '19 at 10:43

2 Answers2

0

The Scanner class has a method for this

Scanner in = new Scanner(System.in);
int num;
if(in.hasNextInt()){
  num = in.nextInt();
  System.out.println("Valid number");
}else{
  System.out.println("Not a valid number");
}

Output 1:

8

Valid number

Output 2:

a

Not a valid number

Ali Azim
  • 160
  • 1
  • 15
0

Your code will like bellow:

try {
            int scannedNumber;
            Scanner scan = new Scanner(System.in);
            System.out.print("Enter An Odd Number\n");
            String userInput = scan.nextLine();

            System.out.println("You pressed :" + userInput);

            scannedNumber = Integer.parseInt(userInput);

            if (scannedNumber % 2 == 0) {
                throw new Exception("Not an odd number");
            }

            System.out.println("You pressed odd number");

        } catch (Exception e) {
            System.out.println("" + e.getMessage());
        }

Here after taking input as String. Then cast as integer. If casting failed then it will throw NumberFormatException. If it is a number then check is it odd? If not odd then it is also throwing an exception.

Hope this will help you.

Thanks :)

Md. Sajedul Karim
  • 6,749
  • 3
  • 61
  • 87