2016-02-10 29 views
1
File Letter Counter 

編寫一個程序,要求用戶輸入一個文件名,然後要求用戶 輸入字符。程序應計算並顯示指定字符在文件中出現的次數。使用記事本或其他文本編輯器來創建可用於測試程序的示例文件 。的Java程式碼實驗室信反

有人能解釋爲什麼計數不工作,我總是得到0

import java.util.Scanner; 

public class TESTTEST 
{ 
public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    System.out.print("Enter file name:"); 

    String linestr = sc.nextLine().toUpperCase(); 
    System.out.print(" Enter character to count:"); 

    char ch = sc.next().toUpperCase().charAt(0); 

    int count = 0; 
    for(char ch0:linestr.toCharArray()) { 
    if(ch0 == ch) 
    count++; 
    } 
    System.out.println(" The character " + "'"+ch+"'" + " appears in the file wc4 " + count + " times."); 
    } 
} 
+0

你是否已經在調試器中檢查了代碼,看看它在做什麼? –

+0

是的,我使用的代碼,它只輸出0的字符出現的數量 – jkjk

回答

1

的輸出。這是因爲你正在檢查在名的文件,性格不文件本身。除非文件位於同一個目錄中,否則您應該採用完整的文件路徑,在這種情況下,您只能使用該名稱(因爲這是本地路徑)。

這裏是你的代碼修改,以允許從文件中讀取:

import java.util.*; 

public class TESTTEST 
{ 
public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    System.out.print("Enter file path:"); 

    //This is the path to the file you want to read from 
    String path = sc.nextLine(); 
    System.out.print(" Enter character to count:"); 

    char ch = sc.next().toUpperCase().charAt(0); 

    //read all lines into a list 
    List<String> lines = Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8); 
    int count = 0; 
    for(String linestr:lines){ 
     for(char ch0:linestr.toCharArray()) { 
      if(ch0 == ch) 
       count++; 
     } 
    } 
    System.out.println(" The character " + "'"+ch+"'" + " appears in the file wc4 " + count + " times."); 
    } 
} 

也請看看documentation for Files.readAllLines,並注意這個功能不適用於在讀取大文件。而不是在大文件上使用ScannerBufferedReader