2015-12-05 22 views
0
public class FileReaderProgram 
{ 
    String stringComponent; 
    int integerComponent; 
    public static void main(String[] args) 
    { 
    Scanner in = new Scanner(System.in); 
    System.out.println("Enter the absolute path of the file"); 
String fileName = in.next();    //Gets the file from the user 
File inFile = new File(fileName); 

Scanner fileReader = new Scanner(inFile);  //Constructs Scanner for reading the file 

while (fileReader.hasNextLine()) 
{ 
    String line = fileReader.nextLine();     //Gets line from the file 
    Scanner lineScanner = new Scanner(line); //Constructs new scanner to analize the line 
    String stringComponent = lineScanner.next(); //Obtains the first word of the data line 
    while (!lineScanner.hasNextInt())  // Checks if there is another word in the string portion of the line 
    { 
    stringComponent = stringComponent + " " + lineScanner.next(); 
    } 
    int integerComponent = lineScanner.nextInt();  //Obtains the integer part of the data line 
    lineScanner.nextLine(); //Consume the newline 
} 

System.out.println(stringComponent); 
System.out.println("integerComponent); 


    } 

} 

我的簡單的小那的應該讀取的文件的多行(包含字符串和一個整數的每一行由一個分離的碼逗號),然後讀回給我,所以我知道它的工作。但是,我在兩個變量的標題中都收到了錯誤消息,並在System.out中突出顯示了它們的位置。我完全困惑,爲什麼,請幫忙?「非靜態變量不能從靜態上下文引用的」我只有1類

+0

刪除開頭的前兩個語句(成員變量)。 – Rao

回答

0

因爲main方法是靜態的,所以它不能訪問FileReaderProgram中定義的任何非靜態變量。這些變量是類成員變量,並且需要FileReaderProgram的一個實例來保存它們。您需要將它們更改爲靜態:

static String stringComponent; 
int integerComponent; 

或創建一個FileReaderProgram實例並通過它訪問它們。

public static void main(String[] args) 
{ 
    FileReaderProgram frp = new FileReaderProgram(); 
    . 
    . 
    . 
} 

既然你正在重新定義與while循環,這些都躲藏在類中定義的,相同的名稱,但下面兩行變量:

System.out.println(stringComponent); 
System.out.println(integerComponent); 

,因爲它們是外循環,正試圖訪問成員變量,這是無效的,就像我上面說的。

+0

在上一個System.out.println('System.out.println(「integerComponent); ') – DBug

+0

中也有一個額外的雙引號謝謝你指出這個錯字,它現在說」變量integerComponent可能不會已初始化「 – iadd7249

+0

不確定,根據您的代碼的當前版本。類成員變量應根據類型初始化爲0,false或null。您是如何解析非靜態變量引用的?可以您發佈最新版本? – DBug

0

這是您完成的代碼嗎?您需要爲一件事導入掃描儀。您還需要導入io。另外,最後一行,你沒有關閉字符串。

除非拋出FileNotFoundException,否則您還需要try catch。

這裏的問題是你有一個類,但是,你只有一個靜態方法,這是主要的。由於main是靜態的,所以你不能在你主要的方法之外實例化變量。你做到了,就好像你有一個對象一樣。

兩種解決方案:將這兩個聲明移到main中,並且您的好東西要去。其他解決方案是在每個變量之前添加關鍵字static。我建議你在main內部移動stringComponent和intComponent以防止不必要的訪問。限制他們的範圍。它在stringComponent上怪異的原因是因爲這是一個對象。如果我沒有記錯,String API中沒有靜態引用。

+0

我在那個例外中添加了,我通過在main中移動聲明來解決了我的問題,但現在它給了我兩個錯誤,說「他們可能還沒有初始化「嗯,JAVA你應該從文件中讀取它,這就是爲什麼!爲什麼這麼說? – iadd7249

+0

做到這一點:String stringComponent =「」;和int intComponent = 0; –

+0

在大多數情況下,這是很好的代碼實踐,在上面的例子中總是用數據實例化一個變量,即使它是零,或者是一個空字符串。如果你在C中實例化沒有值的變量,它可能導致混亂,狗和貓一起生活,世界末日。 –

相關問題