-3

Hi i am learning java for past few days only when i try to execute a simple program i got an ArrayIndexoutofbounds exception during run time pls help me to fix this exception

here is my code

  class Armstrong 
    {
      public static void main(String args[])
       {
         if (args.length!=0) {
            System.out.println("value is required");
            System.exit(0);
           }
         int num = Integer.parseInt(args[0]);
         int n = num;
         int check =0, remainder;
         while(num>0)
          {
            remainder = num%10;
            check = check+(int)Math.pow(remainder,3);
            num = num/10;
          }
         if (check==n)
           System.out.println(n+ "isa armstrong number");
         else 
           System.out.println(n + "is not a armstrong number");
         }
       }
bNd
  • 7,512
  • 7
  • 39
  • 72
Raj
  • 9
  • 1
  • 5
    Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Atri Dec 17 '15 at 05:56
  • 1
    As ashutosh mentioned look at the question and also look at the document to understand how and why it occurs. The args length should be checked for zero, if you want to throw error. You are throwing an error currently if the args length is not equal to zero. – Manglu Dec 17 '15 at 06:04

2 Answers2

5

If you want a value then if (args.length!=0) { should be

if (args.length==0) {

because you terminate when the condition is true.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Change condition from

 if (args.length!=0) 

to

 if (args.length<=0) 

As it throw if args has no any value than it throw this error.

bNd
  • 7,512
  • 7
  • 39
  • 72