有人可以帮助我获得缓冲的阅读器以使用Java吗? [英] Can someone help me to get buffered reader to work in Java?
问题描述
在这里,我正在尝试阅读包含单词和相应缩写的文档。例如。
Here I am trying to read a document that has words and corresponding abbreviations. E.g.
one,1
two,2
easy,ez
每行都是分隔的,单词和缩写之间用逗号分隔。
Each line is separated, and the words are separated from the abbreviations with a comma.
当我希望缓冲的阅读器继续使用
When I want the buffered reader to keep reading lines using
while ((line = br.readLine()) != null)
不会。它只会读取第一行。这意味着它将显示1的缩写,即1。但是,如果我输入另一个值,说2,则会收到此错误消息。
it won't. It will only read the first line. This means it will display the abbreviation for one, which is 1. But if I input another value say two, I get this error message.
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
at java.lang.String.charAt(String.java:658)
at shortener.NewClass.Short(NewClass.java:41)
at shortener.NewClass.main(NewClass.java:26)
Java Result:
这是代码
here's the code
public static String Short(String input) {
try {
FileReader fr = new FileReader("abbreviations.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
for(int i = 0; i <= line.length(); i++) {
if(line.charAt(i) == ','){
String strOrig = line.substring(0, i);
if(strOrig.equals(input)) {
String strAbv = line.substring(line.length()-1);
return strAbv;
}
}
}
}
br.close();
} catch (IOException e) {
out.println("File Not found");
}
return null;
}
推荐答案
您已创建了条件表达式在 for
循环中,因为 i小于或等于line.length()。错了。 i
不应等于行的长度。更改此
You have made the conditional expression in for
loop as i lesser than or equal to line.length(). That's wrong.i
shouldn't be equal to the length of the line. Change this
for(int i = 0; i <= line.length(); i++)
至
for(int i = 0; i < line.length(); i++)
使 i
等于行的长度。索引从 0
开始。因此,有效索引应为 0
到 length-1
you can't make i
equal to the length of line. The index starts from 0
. so, the valid indexes would be from 0
to length-1
这篇关于有人可以帮助我获得缓冲的阅读器以使用Java吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!