0

I am a little bit confused about Array.

While I Run this program I got an error.

class Insurance {
public static void main(String args []) {
    int age;
    String gen;
    String status;
    age = Integer.parseInt(args[0]);
    gen = args[1];
    status = args[2];
    if(status.equalsIgnoreCase("Married"))
     System.out.println("Insurance Given!");
    else if(gen.equalsIgnoreCase("Male") && age>30)
     System.out.println("Insurance Given");
    else if(gen.equalsIgnoreCase("Female") && age>25)
     System.out.println("Insurance Given");
    else 
     System.out.println("Insurance Denied");
     
}

}

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0at Insurance.main(Insurance.java:9)

Atul2922
  • 15
  • 1
  • 7
  • You need to add details about how you run the code and why you expect the args array to have any data in it, as you've written in your code – OneCricketeer Mar 24 '21 at 06:30

2 Answers2

0

You have to pass arguments to a main()

compile by > javac Insurance.java  
run by > java Insurance 50 Male Married

In above case:

args[0] = 50
args[1] = Male
args[2] = Married

If any argument is missing it will throw java.lang.ArrayIndexOutOfBoundsException. You can check number of arguments like this:

if(args.length == 3) {     
    //the last argument is null
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
0

you can run this code using the command line. Go to the file location.

Open command line and Compile your class

javac Insurance.java

then run your class and use this command like this example.

java Insurance.java 12 Male Married

Thanks