所以我在编码方面做了一些相对简单的阅读文件"程序。我收到很多编译错误,所以我开始尝试一次编译一行,看看我在哪里被软管。我到目前为止所处的位置:
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甚至没有#34; stack&#34;作为索引关键字。 Hrmph。
答案 0 :(得分:7)
你不能让代码在这样的类中漂浮。它需要在方法,构造函数或初始化程序中。您可能希望在主方法中使用该代码。
答案 1 :(得分:6)
在声明类的属性/方法时,不能使用方法。
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
}
}