2017-03-03 33 views
-1

我想從文本文件中提取元素,以便可以計算文件中的總字符數。我想用while循環來添加文件中每行的長度,並將其分配給我的角色對象。但是,我已經看到了這種方法的缺陷。我相信使用數組是最好的選擇,但是我對數組的瞭解還不夠充分。我怎樣才能最好地實現這種使用數組的預期行爲?使用數組獲取文件中所有行的字符數

import java.io.*; 
import java.util.Scanner; 

public class CountWords { 
    public static void main(String[] args) throws IOException { 

    File inFile = new File("TestFile.txt"); 
    Scanner input = new Scanner(inFile); 

    int words = 0, cha = 0, character = 0, temp; 

    while(input.hasNext()){ 

     String text = input.nextLine(); 

     temp = text.length(); 

     character = text.length() + temp; 
    } 

    System.out.println("The file contains"); 
    System.out.println(words + " words"); 
    System.out.println(character + " characters"); 
     input.close(); 
    } 
} 
+0

見我的答案在這裏。 http://stackoverflow.com/a/42589718/6657842 – RLD

回答

0

更換

character = text.length() + temp;

character = text.length() + character;

相關問題