java.lang.ArrayIndexOutOfBoundsException error
Hi, please can anyone explain why I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 atTokenScanner1.main(TokenScanner1.java:13
Code:
import java.util.Scanner;
import java text.*;
class TokenScanner1 {
public static void main (String[] args) {
boolean b, b2;
int i;
String s, hits = " ";
Scanner s1 = new Scanner(args[0]);
while (b = s1.hasNext()) {
if (s1.hasNextInt()) {
i = s1.nextInt(); hits += "i"; }
else if (s1.hasNextBoolean()) {
b2 = s1.nextBoolean(); hits += "b"; }
else { s1.next(); hits += "o"; } }
System.out.println ("hits " + hits); } }
Re: java.lang.ArrayIndexOutOfBoundsException error
You're not passing any command line arguments when you call your program and so the args array has size 0 -- has no members. Solution: always pass appropriate command line arguments when you run this program or any program that needs them. Also you should check that the user has done this in your main before trying to get the argument. You could check the length of the args array and if it is 0, warn the user that they're not running the program correctly, and then cleanly exit the program.