. Advertisement .
..3..
. Advertisement .
..4..
I am trying to write a java that returns an invalid answer. I don’t know where the incorrect command is in the “index 0 out of bounds for length 0.” My detail is:
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");
}
}
}
and I end up with the warning message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
Please, suggest the best answer to fix it.
The cause: This java class is being run without any arguments. In such situation,
args[0]
is now present, and the Exception with Error message is now given.Solution: To get rid of the error: Index 0 out of bounds for length 0, you can change the
if
form like this:When your program produces error-free output, the limitless look of printing
k
is achieved by running the program using the input “k”. You can do this by using the java File k command, or by starting it from the IDE with this argument.Run the code on cmd and run MyProgram abc Java xyz. Then args will contain “abc”, xyz”.