簡體   English   中英

如何使用循環計數文本文件中的某些字符

[英]How to count certain characters in a text file using loops

我需要詹姆斯·喬伊斯(James Joyce)進行的有關計算尤利西斯(Ulysses)文字中所有元音的項目的幫助。 我不確定如何使程序讀取在項目的根文件夾中插入的文本文件。 我也不確定如何制作一個循環來計算所有元音。 這就是我到目前為止所擁有的。

public static void main(String[] args) throws FileNotFoundException {

    System.out.println("Vowel counts in Ulysses by James Joyce:");

    int a = 0;
    int e = 0;
    int i = 0;
    int o = 0;
    int u = 0;

    System.out.println("a = " + a);
    System.out.println("e = " + e);
    System.out.println("i = " + i);
    System.out.println("o = " + o);
    System.out.println("u = " + u);

        FileReader reader = new FileReader("ulysses.txt");
        Scanner input = new Scanner(reader);

        while (input.hasNextLine()) {
            String line = input.nextLine();
        }


    }}

輸出應如下所示(所有數字均正確):

Vowel counts in Ulysses by James Joyce:  
a = 94126   
e = 143276  
i = 82512  
o = 92743  
u = 33786

我不得不這樣做一次,我認為這與此類似。

while (input.hasNextLine()) {
        String line = input.nextLine();
        //toUpperCase() normalizes all the letters so you don't have to count upper and lower
        line.toUpperCase(); 
        char[] c = line.toCharArray(); 
        for (int j = 0; j < c.length(); j++)
        switch(c[i])
        {

        case "A";
            a++;
        case "E";
            e++;
        case "I";
            i++;
        case "O";
            o++;
        case "U";
            u++;

        }


    }

import java.util.Scanner;

公共類Smashcode {

public static void main(String[] args) throws Exception {
    // Create a File instance
    java.io.File file = new java.io.File("samplefile.txt");

    // Create a Scanner for the file
    Scanner input = new Scanner(file);

    // Create the Content String        
    String fileContent = "";

    // Read data from a file
    while (input.hasNext()) {
        fileContent += input.next() + " ";
    }
    // Close the file
    input.close();

    //Split the string into a character array
    char[] charArr = fileContent.toCharArray();

    //loop through every character to find the vowels
    int counter = 0;
    for(char c : charArr)
    {
          if(c == 'a')
               counter_a++;
          if(c == 'e')
               counter_b++;
          if(c == 'i')
               counter_i++;
          if(c == 'o')
               counter_o++;
          if(c == 'u')
               counter_u++;
    }

    //number of vowels
    System.out.println("Number of Vowels: " + (counter_a+counter_e+counter_o+counter_i+counter_u));
    System.out.println(counter_a);
    System.out.println(counter_e);
    System.out.println(counter_i);
    System.out.println(counter_o);
    System.out.println(counter_u);

    }}

希望你喜歡我的工作。快樂編碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM