javastringfile-iobufferedreadercoderunner

Index out of range error with exception in thread main


I'm a beginner learning to program in Java. I have written a program that reads words from a file and prints them with spaces in-between in addition to as they exist in the file. When I run my program I get an error denoting an "exception in thread main".

Any help would be appreciated!

Thank You!

The File I'm reading from:

APPLE
ELABORATE
FUTURE
PROOF
LOGICAL

My Program:

//imports
import java.awt.*;
import java.util.*;
import java.io.*;

class Untitled {
    public static void main(String[] args) throws IOException {

        //variables
        String filePath = "/Users/cameronburgess/Programming/I:O/words.txt";
        String word = "";
        int cv = 0;
        String spacedWord = "";

        //objects
        BufferedReader readBot = new BufferedReader(new FileReader (filePath));

        //user facing
        System.out.println("This program will read from a File at :" + filePath);
        System.out.println();
        while (readBot.readLine() != null) {
            word = readBot.readLine();

            //spliter
            while (word.length() != cv) {   
                    spacedWord = spacedWord + " " + word.charAt(cv);
                    cv = cv + 1;
                }   
                System.out.println(word + " OR " + spacedWord);
        }
    }       
}

The Console Return:

This program will read from a File at :/Users/cameronburgess/Programming/I:O/words.txt

ELABORATE OR  E L A B O R A T E
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 9
    at java.lang.String.charAt(String.java:686)
    at Untitled.main(Strings6.java:36)

Solution

  • Have a try to make some change for the while-loop,

    You need to reset the value to cv =0; spacedWord=""; when you are trying to split the word.

    like,

     while ((word=readBot.readLine()) != null) {
            //spliter
            cv =0;
            spacedWord="";
            while ( cv <word.length()) {   
                    spacedWord = spacedWord + " " + word.charAt(cv);
                    cv = cv + 1;
                }   
                System.out.println(word + " OR " + spacedWord);
        }
    

    You will get the result as follows:

    This program will read from a File at :TEST.txt
    
    APPLE OR  A P P L E
    ELABORATE OR  E L A B O R A T E
    FUTURE OR  F U T U R E
    PROOF OR  P R O O F
    LOGICAL OR  L O G I C A L