+ 1
Error in Java program .
I had written a java code in Notepad , And compiled it through command prompt , it compiled successfully but when I trying to run it in cmd it shows : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0 . How to solve this error ? import java.io.*; class Addition1 { public static void main(String args[]) { int no1,no2,add; no1=Integer.parseInt(args [0]); no2=Integer.parseInt(args [1]); add=no1+no2; System.out.print("The Addition of two number is : "+add); }} //output in cmd : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0 at Addition1.main(Addition1.java:7)
8 Respuestas
+ 5
Try to run it giving two arguments e.g.
java Addition1 21 21
Tell me does it work?
+ 6
How did you run the code? like what did you type on the console. Did you provide any argument following the filename?
+ 4
Happy to hear that 😁
And to anticipate such error, you can check <args>.length before trying to use any of its elements 👍
+ 4
Hrutik Bhalerao
args is used to read data through command line so if you use it then you must have pass data otherwise you may get error.
If you want to take input at runtime then use scanner object or buffer reader.
+ 3
Hrutik Bhalerao
You are reading arguments value so obviously it should have 2 arguments in command line because you have written args[0] and args[1]
args[0] means first value of array args so if you don't provide any argument through command line then you get error.
+ 2
I run it through cmd , their firstly I typed javac Addition1.java
(Addition1 is the class and file name). Then it compiled successfully without any error , next I typed java Addition1 (for running ) , after this it directly showing that above error without taking any input or anything else.
+ 2
Yes it works 😀 . It's showing 42 . Thank you for your help , first I thought that it would take input after running code in next line . Now it has cleared that input must be entered at the same time.
+ 2
Thank you A͢J - S͟o͟l͟o͟H͟e͟l͟p͟e͟r͟ sir . I recently started learning Java