0

Here i am getting this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

public static void main(String[] args) {
    Scanner keyboard  = new Scanner(System.in);
    String input = keyboard.nextLine();
    System.out.println(input);
    while(true){
        if(args[0].equals("k")){
            System.out.println("k");
        }
    }
}
Karthik Putchala
  • 19
  • 1
  • 1
  • 4
  • 1
    Perhaps args.length == 0? – NomadMaker Jun 28 '20 at 05:41
  • 1
    Have you started this program by providing input via console? args get its value via console. If not args[] will be empty – Sabareesh Muralidharan Jun 28 '20 at 05:42
  • 1
    Instead of `args[0].equals("k")`; you need to use `input.equals("k")`. `args` is the argument which needs to be passed through command line at the time of running the `.class` file through console. Something like `java Your_Class_Name k` –  Jun 28 '20 at 06:34
  • @karthik-putchala Can you accept my answer, as it is precise and detailed on the point? – zhrist Nov 19 '20 at 20:09

5 Answers5

0

You need run the code on cmd as java MyProgram abc xyz then args will contain ["abc", "xyz"].Maybe you are not doing that right now and therefore getting the error.

Sanjanah
  • 21
  • 3
0

You need to provide Command Line Arguments like so:

java MyClass k foo bar

These arguments are passed to the array args[] which will then contain {"k", "foo", "bar"}

Therefore args.length will be 3 and args[0] will be k

Ishan Goel
  • 88
  • 1
  • 8
0

If you are executing through IDE and not setting arguments OR not passing command line arguments while running through cmd, you'll get this error.

But for this program, even if you pass arguments, it will run in infinite loop probably as while condition is always true.

0

You are executing this java class without arguments. In that case, args[0] does now exist, and thus the Exception with Error message.

You can modify the if in this form:

if(args[0].equals("k") && args.length > 0 )

so you do not get exception with message

Index 0 out of bounds for length 0

Your program is producing output without error, when Running the program with argument "k" produces the infinite look of printing k. For this you need to run command the java printKjavaFile k , or start it from IDE with this argument.

zhrist
  • 1,169
  • 11
  • 28
0

You are doing 2 things at the same time:

  • ask for user input via stdin, when the program is running already
  • parsing the args[], which should be given when the program starts to run

and expect they work together. But they are different.

I suppose you run the app like: java MyClass without adding extra args after this. You can:

  • provide arg k after java MyClass, so args[] becomes a non-empty array
  • stop trying to use args, but just focus on input, which is the line you read from user input.
WesternGun
  • 11,303
  • 6
  • 88
  • 157