【发布时间】:2013-12-09 17:11:21
【问题描述】:
我是一名学习 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)
【问题讨论】:
-
您应该使用
StringBuilder而不是连接运算符来重复连接字符串。
标签: java string file-io bufferedreader coderunner