2013-02-22 33 views
0

程序需要計算並顯示指定的charector出現在文本文件中的次數。計數字母出現

目前總數爲零。我不是如果我應該使用不同的循環,我也嘗試使用'for'循環。

// Hold user input and sum 
String fileName; // Holds the name of the file 
String letter;  // Letter to search for in the file 
int total = 0;  // Holds the total number of characters in the file 


// Get the name of the file and character from the user 
fileName = JOptionPane.showInputDialog("Please enter the name of a file:"); 
letter = JOptionPane.showInputDialog("Please enter a letter contained in the string"); 


// Open the file for reading 
File file = new File(fileName);   
Scanner inputFile = new Scanner(file); // Declare new scanner object for file reading 


// Set accumulator to zero 
int count = 0; 

if (inputFile.nextLine().equalsIgnoreCase(letter)) {         

    count++;   // add letter occurrence 

    total += count; // add the letter occurrence to the total 
} 
+1

是每行只有一個字母? – RNJ 2013-02-22 09:47:13

+0

每一行都是一個單詞,.txt是一個段落 – 2013-02-22 09:57:08

回答

5
BufferedReader reader = new BufferedReader(new FileReader("somefile.txt")); 
    int ch; 
    char charToSearch='a'; 
    int counter=0; 
    while((ch=reader.read()) != -1) { 
     if(charToSearch == (char)ch) { 
      counter++; 
     } 
    }; 
    reader.close(); 

    System.out.println(counter); 

I這有什麼幫助?

+0

這個工程,只需調整大小寫不敏感 謝謝! – 2013-02-22 10:26:11

0

這個答案假定您的文本文件中的每行只包含一個字母,就像您的問題所示。

你需要用你的if語句在一個循環中你目前只檢查文件的第一行:

 while(inputFile.hasNext()) { 
     if (inputFile.nextLine().equalsIgnoreCase(letter)) {         

      count++;   // add letter occurrence 

      total += count; // add the letter occurrence to the total 
     } 
    } 

你也可以更換:

count++; 
total+= count; 

total++; 
+0

用包裝的'while'循環更新,仍然不起作用,0次出現的字母 – 2013-02-22 09:54:53

+0

可以粘貼示例文本文件 – cowls 2013-02-22 09:57:40

0
String line="" 
while(inputFile.hasNext()) { 
    line = inputFile.nextLine(); 
    for(int i=0; i<line.length(); i++){ 
    if (line.charAt(i)== letter)          
     count++;   

} 
} 
1

有錯誤你code.Correct代碼如下─

String fileName; // Holds the name of the file 
    String letter;  // Letter to search for in the file 

    // Get the name of the file and character from the user 
    fileName = "C:\\bin\\GWT.txt"; 
    letter = "X"; 


    // Open the file for reading 
    File file = new File(fileName);   
    Scanner inputFile = new Scanner(file); // Declare new scanner object for file reading 


    // Set accumulator to zero 
    int count = 0; 
    while(inputFile.hasNext()) { 
     if (inputFile.nextLine().toLowerCase().contains(letter.toLowercase())) { 
      count++;   // add letter occurrence 
     } 
    } 
    System.out.println(count); 
+0

此代碼返回一個數字,但我認爲該數字不正確... – 2013-02-22 10:13:11

+0

這也是區分大小寫的 – 2013-02-22 10:14:00

+0

blnr,編輯上面的代碼以進行不區分大小寫的檢查。您也可以參考以下內容 - http://stackoverflow.com/questions/5054995/how-to-replace-case-insensitive-literal-substrings-in-java – JRR 2013-02-22 10:34:40