7

所以我正在编写我认为是一个相对简单的“读取文件”程序的代码。我得到了很多编译错误,所以我开始尝试一次编译一行,看看我在哪里被灌输了。这是我到目前为止的位置:

import java.nio.file.*;
import java.io.*;
import java.nio.file.attribute.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
import java.text.*;
//
public class ReadStateFile
{
    Scanner kb = new Scanner(System.in);
    String fileName;     /* everything through here compiles */
    System.out.print("Enter the file to use: ");
}

注意:这是从另一个类中的方法调用的构造函数的前三行。构造函数的其余部分在下面继续......当然,上面没有第二个花括号......

fileName = kb.nextLine();
Path file = Paths.get(fileName);
//
final String ID_FORMAT = "000";
final String NAME_FORMAT = "     ";
final int NAME_LENGTH = NAME_FORMAT.length();
final String HOME_STATE = "WI";
final String BALANCE_FORMAT = "0000.00";
String delimiter = ",";
String s = ID_FORMAT + delimiter + NAME_FORMAT + delimiter + HOME_STATE + delimiter + BALANCE_FORMAT + System.getProperty("line.separator");
final int RECSIZE = s.length();
//
byte data[]=s.getBytes();
final String EMPTY_ACCT = "000";
String[] array = new String[4];
double balance;
double total = 0;
}

编译后,我得到以下信息:

E:\java\bin>javac ReadStateFile.java
ReadStateFile.java:20: error: <identifier> expected
        System.out.print("Enter the file to use: ");
                        ^
ReadStateFile.java:20: error: illegal start of type
        System.out.print("Enter the file to use: ");
                         ^
2 errors

E:\java\bin>

我到底错过了什么?有人可以向我拍摄一段代码以生成堆栈跟踪吗?我只是在阅读 java 文档时感到困惑,而 Java Tutotrials 甚至没有“stack”作为索引关键字。哼。

4

2 回答 2

8

声明类的属性/方法时不能使用方法。

public class ReadStateFile
{
    Scanner kb = new Scanner(System.in);
    String fileName;     /* everything through here compiles */
    System.out.print("Enter the file to use: "); //wrong!
}

代码应该是这样的

public class ReadStateFile
{
    Scanner kb = new Scanner(System.in);
    String fileName;     /* everything through here compiles */

    public void someMethod() {
        System.out.print("Enter the file to use: "); //good!
    }
}

编辑:根据您的评论,这就是您要实现的目标:

public class ReadStateFile
{

    public ReadStateFile() {
        Scanner kb = new Scanner(System.in);
        String fileName;     /* everything through here compiles */
        System.out.print("Enter the file to use: ");
        //the rest of your code
    }
}
于 2012-04-26T01:01:52.217 回答
7

你不能让代码在这样的类中四处游荡。它要么需要在方法、构造函数或初始化程序中。您可能打算在 main 方法中包含该代码。

于 2012-04-26T01:02:08.160 回答