索引超出范围错误,主线程中出现异常

时间:2013-11-25 05:16:16

标签: java string file-io bufferedreader coderunner

我是初学者,学习用Java编程。我编写了一个程序,它从文件中读取单词,并在文件之间存在空格。当我运行我的程序时,我收到一个错误,表示“主线程中的异常”。

任何帮助将不胜感激!

谢谢!

我正在阅读的文件:

APPLE
ELABORATE
FUTURE
PROOF
LOGICAL

我的计划:

//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);
        }
    }       
}

控制台返回:

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)

3 个答案:

答案 0 :(得分:2)

尝试对while循环进行一些更改,

当您尝试拆分单词时,需要将值重置为cv =0; spacedWord="";

 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);
    }

您将得到如下结果:

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

答案 1 :(得分:1)

每次阅读行时,您应该将cv计数器重新初始化为0:

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

答案 2 :(得分:0)

如果您不想在最后处理单词的长度,请使用带有字符数组的foreach循环,如下所示

    char[] charactersArray = word.toCharArray();
    for (char character : charactersArray) {
            //do whatever you want to with the 'character'
    }