2012-04-26 27 views
2

所以我在編碼厚厚的東西,我雖然會是一個相對簡單的「讀取文件」程序。我收到大量的編譯錯誤,所以我開始只是試圖編譯一行,看看我在哪裏弄到。這裏就是我至今:爲什麼System.out.print()不起作用?

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甚至沒有將「堆棧」作爲索引關鍵字。 Hrmph。

+0

請編輯您的問題以顯示_exactly_您的構造函數的外觀。嘗試查找語法錯誤時,甚至沒有看到實際的代碼將是浪費時間。 – David 2012-04-26 01:10:46

+0

@David - 剛剛發佈了構造函數的其他位 – dwwilson66 2012-04-26 01:15:21

回答

5

聲明類的屬性/方法時,不能使用方法。

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

我忘了 - 剛剛添加 - 這是構造函數的第一部分。我仍然需要在這堂課中使用一種方法嗎?或者從另一個類的方法中調用這個構造函數也會做同樣的事情? – dwwilson66 2012-04-26 01:08:03

+0

@ dwwilson66這裏的事情是你的代碼不在構造函數中,而是在類定義中。 – 2012-04-26 01:09:46

+0

@Luigi BINGO!繼承代碼,缺乏睡眠。我現在覺得自己像個白癡。啊。謝謝。 – dwwilson66 2012-04-26 01:17:07

7

你不能有代碼只是在這樣的班級中漂流。它需要在方法,構造函數或初始化器中。您可能打算在您的主要方法中使用該代碼。

+0

@Jeffrey ......剛澄清;這是構造函數的第一部分。 – dwwilson66 2012-04-26 01:06:25

+1

@ dwwilson66然後用該構造函數發佈一個片段 – Jeffrey 2012-04-26 01:07:29