为什么 System.out.print() 不起作用?

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教程甚至没有将“stack”作为索引关键字。唉。


请编辑您的问题,以显示构造函数的确切外观。如果您甚至没有查看实际代码就试图查找语法错误,那么这将是浪费时间。 - David
@David - 刚刚发布了构造函数的其他部分。 - dwwilson66
2个回答

9

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

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
    }
}

我忘了并刚刚添加,这是构造函数的第一部分。我是否仍然需要在此类中使用方法?还是从另一个类的方法中调用此构造函数会产生相同的效果? - dwwilson66
@dwwilson66 这里的问题是你的代码不在构造函数中,而是在类定义中。 - Luiggi Mendoza
@Luigi 太好了!继承的代码,睡眠不足。现在感觉像个白痴。唉。谢谢。 - dwwilson66

7

您不能让代码像那样在类中漂浮。它必须在方法、构造函数或初始化器中。您可能是想把那段代码放在主方法中。


@ Jeffrey... 刚刚澄清了一下:这是构造函数的第一部分。 - dwwilson66
1
@dwwilson66 然后发布一个包含该构造函数的代码片段。 - Jeffrey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接