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"); } }
} 4 5 Answers
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.
You need to provide Command Line Arguments like so:
java MyClass k foo barThese 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
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.
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.
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
kafterjava MyClass, soargs[]becomes a non-empty array - stop trying to use
args, but just focus oninput, which is the line you read from user input.