1

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

    }

}

文件.txt

1
2
3
foo
HopeFullyThisWillChange
5
6
7
8
9
10

错误...

java.lang.NoSuchMethodError: main
Exception in thread "main" 

谢谢你的帮助!

4

3 回答 3

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++;
}
于 2011-03-06T22:30:36.447 回答
0

此错误根本与您的代码无关,您只是在尝试执行错误的类。检查您的 IDE 配置,并在命令行上使用java MyMainClass.

于 2011-03-06T22:29:59.693 回答
0

不需要mainstatic

于 2011-03-06T22:31:55.770 回答