0

I'm trying to to read the file contents into a character array using the scanner class and I keep getting a string index out of bounds error from my code and I'm not sure what's wrong

    File fileName = null;
    if(0<args.length) {
        fileName = new File(args[0]);
    }
    Scanner s = null;
    try {
        s = new Scanner(fileName);
        s.useDelimiter(",");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    char[]array = new char[26];
    while(s.hasNext()) {
        for(int i=0; i<27; i++) {
            array[i] = s.next().charAt(i);
        }
    }
Phantômaxx
  • 36,442
  • 21
  • 78
  • 108

2 Answers2

2

As far as I can tell, your code is equivalent to the following, which has no out of bounds exceptions

char[]array;
while(s.hasNext()) {
    array = s.next().toCharArray();
}

However, after that while loop, your array will only equal the very last scanned value.

If you have individual comma separated characters, you can use the following. You do not need a loop within the existing loop

char[]array = new char[26];
int i = 0;
while(s.hasNext()) {
    array[i++] = s.next().charAt(0);
}

In any case, I suggest using StringTokenizer rather than a Scanner

OneCricketeer
  • 126,858
  • 14
  • 92
  • 185
1

In your for loop, you are trying to access a[26] but you have declared memory for 26 characters. So you can access only a[0] to a[25].

Deadpool
  • 94
  • 10