0

我是一个学习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)
4

3 回答 3

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
于 2013-11-25T05:22:41.243 回答
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);
于 2013-11-25T05:20:44.197 回答
0

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

    char[] charactersArray = word.toCharArray();
    for (char character : charactersArray) {
            //do whatever you want to with the 'character'
    }
于 2013-11-25T05:25:05.173 回答