在java中读取和替换行

Use*_*er1 1 java nosuchmethoderror

我试图逐行将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();

    }

}
Run Code Online (Sandbox Code Playgroud)

FILE.TXT

1
2
3
foo
HopeFullyThisWillChange
5
6
7
8
9
10
Run Code Online (Sandbox Code Playgroud)

错误...

java.lang.NoSuchMethodError: main
Exception in thread "main" 
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

Mat*_*all 7

main方法必须是static:

public static void main(String[] args) throws IOException {
    // snip...  
}
Run Code Online (Sandbox Code Playgroud)

编辑 - 解决真正的问题

循环只运行一次,因为在第一次通过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++;
}
Run Code Online (Sandbox Code Playgroud)