public static void main(String[] args) {
    int n;
    n = Integer.parseInt(args[0]);
    if(n>100)
    {
        System.out.println("The number is greater than 100.");
    }
}
            Asked
            
        
        
            Active
            
        
            Viewed 254 times
        
    -2
            
            
        - 
                    2Did you pass any arguments when you ran this? – Dawood ibn Kareem Mar 07 '17 at 10:41
- 
                    How many elements are there in `args`? – Biffen Mar 07 '17 at 10:41
- 
                    @VeeraKannadiga I doubt whether that will help much. I suspect that the issue here is simply that Shanti doesn't know how to get NetBeans to pass command line arguments to the program. – Dawood ibn Kareem Mar 07 '17 at 10:44
- 
                    no @DavidWallace – shanti Mar 07 '17 at 10:47
- 
                    yes sir you are right .I'm actually new to java @DavidWallace – shanti Mar 07 '17 at 10:48
- 
                    This page explains how to do it. http://sanduntech.blogspot.co.nz/2015/03/java-command-line-arguments-in-netbeans.html – Dawood ibn Kareem Mar 07 '17 at 10:51
- 
                    Ty sir @DavidWallace – shanti Mar 07 '17 at 10:57
2 Answers
1
            The args array contains the arguments given to the program (command line parameters). You can give these either via:
- the project run settings in an IDE
- the command line
If you run your program without any arguments, the array will however be empty. Therefore, no item will be on index 0 and the ArrayIndexOutOfBoundsException is thrown.
If you want to fix this, you will either have to:
- pass at least one argument via one of the mentioned methods aboven.
- change your code so it does not depend on command line parameters.
 
    
    
        PimJ
        
- 38
- 7
0
            
            
        change your code this way:
public static void main(String[] args) {
    if(args != null && args.length > 0) {
    int n;
    n = Integer.parseInt(args[0]);
    if(n>100) {
        System.out.println("The number is greater than 100.");
    }
    }
}
If you want also to handle the fact that args[0] could not be an integer, you can change it this way:
public static void main(String[] args) {
        if(args != null && args.length > 0) {
        int n;
try {
        n = Integer.parseInt(args[0]);
        if(n>100) {
            System.out.println("The number is greater than 100.");
        }
catch(NumberFormatException e) {
System.err.println("Not a number");
}
        }
    }
 
    
    
        ChaSIem
        
- 493
- 1
- 6
- 18
 
    