Home » Java » InputMismatchException is not working with Integer.parseInt( args [0]) ; than how can you get the exception to work, without a scanner

InputMismatchException is not working with Integer.parseInt( args [0]) ; than how can you get the exception to work, without a scanner

Posted by: admin April 25, 2018 Leave a comment

Questions:

So if a user enters age as fishs instead of a integer a InputMismatchException prints “Error in the input enter a number”.
or if the user does not enter anything in cmd (command line) than a ArrayIndexOutOfBoundsException prints “Not enough arguments on the command line”

Fuuthermore No scanner should be used. And age = Integer.parseInt( args [0]) ; must be used to convert age from character to integer

Modify your program in Question to take the age of the user from the command line as the program runs. Your program should handle problems if the user does not input a number on the command line or makes an error in input.

Here is the code:

 public class age {

public static void main(String args[]){
    int age = 0;




     // try   
    try{
       // convert age from character to integer 
       age = Integer.parseInt( args [0]) ;

       // check input age value
       // if ueser inputs age less or equal to 12
        if(age<= 12)
        System.out.println("You are very young");
        // if user enters age larger than 12 and less than 20
         if(age > 12 && Age < 20)
            System.out.println("You are a teen");
        // if user enters age larger than 20
       if (age > 20)
            System.out.println("wow" +Age+" is very old");
    }
    catch(InputMismatchException e){
       System.out.println("Error in the input enter a number");
    }
 catch ( ArrayIndexOutOfBoundsException exception0) {System.out.println   ("Not enough arguments on the command line" ) ; }
  }   
}   
Answers: