Brian Puszkar II
Brian Puszkar II

Reputation: 99

Array index out of bounds and causing error?

I know this is an easy fix but it is killing me. I have tried to look at other questions and cant find any that have helped. This is my last option to post here because I am running out of time to finish this program. This program reads numbers from a file and prints out the word vale of each digit ie. 30 : three zero, 150 : one five zero

the error shows out of bounds at the line of code

System.out.print(alsoWords[((int) digit - 0)] + " ");

    package main;

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;

    public class Main {

// can use String array instead of Map as suggested in comments
private static final String[] alsoWords = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

public static void main(String args[]) //throws FileNotFoundException 
{
    Scanner fin = null;
 //           Scanner scanner = new Scanner(new File("translates.txt"));
 //
 //           while (scanner.hasNextInt())
    {
        try {
            fin = new Scanner(new File("C:\\Users\\Brian2\\Documents\\NetBeansProjects\\main\\src\\main\\translate.txt"));
        } catch (FileNotFoundException e) {
            System.err.println("Error opening the file translates.txt");
            System.exit(1);
        }
        while (fin.hasNext()) {
            int i = 0;
            i ++;
            char[] chars = ("" + fin.nextInt()).toCharArray();

            System.out.print(String.valueOf(chars) + ": ");

            // for each digit in a given number
            for (char digit : chars) {
                System.out.println(i);
                System.out.print(alsoWords[((int) digit - 0)] + " ");

            }
            System.out.println();
        }
    }

    fin.close();

}
 }

Upvotes: 0

Views: 75

Answers (1)

Dour High Arch
Dour High Arch

Reputation: 21722

Step through your code in the debugger. Inspect the values of each variable.

for (char digit : chars)

digit is a Unicode character.

(int) digit

You are getting the Unicode point of digit. For ASCII characters this is the same as the ASCII value. For example, the ASCII value of NUL is zero. The ASCII value of the character 0 is 48. Suppose the first character was a zero. You are getting:

48 - 0

Which is 48.

alsoWords[48]

is out of bounds. You want:

alsowords[(int)digit - (int)'0']

How to deal with characters before '0' is left as an exercise for the reader.

Upvotes: 2

Related Questions