2015-11-02 74 views
1

我剛剛得到了一些家庭作業,讓我做這個奇怪的任務。老師希望我們將各種句子分解成單詞。老師已將這些文件放入通過掃描儀導入的文件中。如何將字符串拆分爲字符而不使用拆分方法或使用數組?

老師要我們然後用這句話,來計算長度,單詞的數量應與詞的數量沿着循環的每個迭代增加。

文件總是以「#」字符結束,因此這正是我開始。

這裏是我迄今爲止現在

class Assignmentfive 
    { 
private static final String String = null; 

public static void main(String[] args) throws FileNotFoundException 
{ 
    Scanner scan = new Scanner(new File("asgn5data.txt")); 

    String fileRead = " "; 
    System.out.print(fileRead); 
    double educationLevel = 0; 
    double wordCount = 0; 

    while (fileRead != "#") 
    { 
    fileRead = scan.nextLine();  

    int firstIndex = fileRead.indexOf(" "); 
    String strA = fileRead.substring(0,firstIndex); 
    System.out.print(strA); 
    int strLength = strA.length(); 
    wordCount++; 
    } 

,有更多的底部,也就是我的計算,我無法弄清楚如何從文件

任意抽取一個字一個字提示?

Thanks``

+0

你在正確的軌道上。你只需要用'fileRead'來做更多的事情。在找到一行中的第一個單詞後,您需要在同一行中檢查更多內容。 – Cruncher

+2

'FILEREAD = 「#」' - > [?我如何在Java中比較字符串(http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Pshemo

回答

0

決不測試String平等==(這是參考身份,不與Object類型的價值認同你想.equals)。您可以使用Scanner(String)構造函數構造一個新的Scanner產生從指定字符串掃描的值。另外,你永遠不close D本Scanner(由File的支持,這是一個資源泄漏)。您可以明確地致電close,但我更喜歡try-with-resources Statement。喜歡的東西,

try (Scanner scan = new Scanner(new File("asgn5data.txt"))) { 
    int wordCount = 0; 
    while (true) { 
    String fileRead = scan.nextLine(); 
    if (fileRead.equals("#")) { 
     break; 
    } 
    Scanner wordScanner = new Scanner(fileRead); 
    while (wordScanner.hasNext()) { 
     String word = wordScanner.next(); 
     System.out.println(word); 
     int wordLength = word.length(); 
     wordCount++; 
    } 
    } 
} catch (Exception e) { 
    e.printStackTrace(); 
} 
+0

喜人!謝謝!是否有任何可能的方法讓這個過程一次一行地完成?文件中有不同的行。 –

+0

@Jon這樣做一次只能通過一行。然後一次一行地檢查每行中的每個單詞。 –

+0

是的,不過我一句一句地看着它,就像句子一樣,得到所有的單詞的平均長度,然後移動到第二句話,然後想法? –