我试图逐行将file.txt读入java,然后当一行为“foo”时,我将其后面的行设置为“lineAfterFoo”,然后将其输出给用户。
我的Java代码......
public void main(String[] args) throws IOException {
try {
FileReader someFile = new FileReader("file.txt");
BufferedReader input = new BufferedReader(someFile);
int i = 0;
String[] line;
line = new String[10];
line[i] = input.readLine();
while(line[i] != null) {
line[i] = input.readLine();
if (line[i] == "foo") {
i = i + 1;
line[i] = "lineAfterFoo";
}
i = i + 1;
}
for (int number = 1; number < i; number++) {
System.out.println(line[number]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FILE.TXT
1
2
3
foo
HopeFullyThisWillChange
5
6
7
8
9
10
错误......
java.lang.NoSuchMethodError: main
Exception in thread "main"
感谢您的帮助!
答案 0 :(得分:7)
main
方法必须为static
:
public static void main(String[] args) throws IOException {
// snip...
}
循环只运行一次,因为在第一次通过while
正文后,i
将等于1
。此时line[1]
为空,因为您没有读过任何内容。这是使用的典型习语(注意变量名称的变化):
int i = 0;
String line = null;
String[] lines = new String[10];
// read the next line and immediately check to see if it's null
// also make sure that i doesn't go out of range
while ((line = input.readLine()) != null
&& i < lines.length) {
lines[i] = line;
// Use .equals() (not ==) when comparing strings!
if ("foo".equals(line)) {
i++; // shorter form of i=i+1
lines[i] = "lineAfterFoo";
}
i++;
}
答案 1 :(得分:0)
这个错误根本与你的代码无关,你只是试图执行错误的类。检查IDE配置,并使用java MyMainClass
在命令行上进行测试。
答案 2 :(得分:0)
main
不需要static
吗?