2013-12-10 51 views
0

我試圖獲得「Lenore」在詩中的次數以及總字數。我收到第13行的錯誤,請幫忙。我很新,似乎無法掌握如何正確地訂購代碼。標識符錯誤?

package theraven; 

import java.io.*; 
import java.util.Scanner; 
import java.util.logging.Level; 
import java.util.logging.Logger; 

public class lenore { 

    Scanner myscanner = new Scanner("/Users/karaleamann/Desktop/theraven.txt"); 

    public int countWord(String Lenore, File"/Users/karaleamann/Desktop/theraven.txt") { 
     int count = 0; 
     while (myscanner.hasNextLine()) { 

      String nextToken = myscanner.next(); 

      if (nextToken.equalsIgnoreCase(Lenore)) 
       count++; 
     } 
     return count; 
    } 

    public int countAll() { 
     File file = new File("/Users/karaleamann/Desktop/theraven.txt"); 
     Scanner sc = null; 
     try { 
      sc = new Scanner(new FileInputStream(file)); 

     } catch (FileNotFoundException ex) { 

      Logger.getLogger(lenore.class.getName()).log(Level.SEVERE, null, ex); 
     } 

     int count = 0; 
     while (sc.hasNext()) { 
      sc.next(); 
      count++; 
     } 
     System.out.println("Number of words: " + count); 
     return 0; 

    } 

} 
+0

調用Lenore的方法似乎也有問題。在主要我有:lenore myLenore = new lenore(); myLenore.countWord();但我不確定要在()中放什麼? – user3085151

回答

0

你不能做到這一點在Java中:

public int countWord(String Lenore, File "/Users/karaleamann/Desktop/theraven.txt") 

我相信你的意思是這個:

public int countWord(String Lenore, File theFile) 

的參數theFile實際值必須提供當通話該方法,而不是在參數聲明期間,它不以那種方式工作。

2

首先,您沒有Main方法,這是執行一個類所需的方法。其次,您以無效的方式定義countWord方法。

更改您的類名勒諾駝峯模式,類名應該有大寫首字母

public int countWord(String Lenore, File "/Users/karaleamann/Desktop/theraven.txt") 

名字你不能做到這一點。你必須通過只是參數

it would be something like: 

public int countWord(String lenore, File file){ 
          //^ variables name should be 
          //  in camelCase 
             //^you pass a File variable 
             // to the method. 

但既然你定義你的類,你不需要將文件傳遞給該方法的掃描儀,你需要改變你的掃描儀是這樣定義的:

new Scanner(new File("/Users/karaleamann/Desktop/theraven.txt")); 

然後你的方法countWord應該是countWord(String lenora)

你有兩種方法什麼都不做。一種是使用掃描儀,但從未被調用過。另一個你根本找不到任何東西。

您的countAll方法是最接近您的解決方案,所以讓我們堅持下去。

你應該改變這部分

while(sc.hasNext()){ 
    String lineText = sc.next(); 
    if (lineText.indexOf("Lenora")>-1){ 
     count++; 
    } 
} 

然後創建一個主要方法來啓動程序

public static void main(String [] args){ 
    Lenore l = new Lenore(); 
    l.countAll(); 
} 

當然,這不是理想的代碼。您必須將其演變爲更邏輯的代碼。分離任務,僅在需要時創建資源。但它現在應該工作。