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