简体   繁体   English

如何将多行 txt 添加到数组中并将每个字母与用户输入的字母进行比较?

[英]How do I add multiple lines of txt into an array and compare each letter to a user-input letter?

I'm trying to create a program that reads a txt document and counts the occurrences of a letter that the user inputs.我正在尝试创建一个程序来读取 txt 文档并计算用户输入的字母的出现次数。 It seems that my for-loop to index the letters is incorrect because it only reads the first or last line of the document.我的 for 循环索引字母似乎不正确,因为它只读取文档的第一行或最后一行。 Any ideas?有任何想法吗?

The txt file contains: txt 文件包含:

Porsche GT2 RS

Lamborghini Huracan Evo

Mercedes Benz S 63 AMG

Merces Benz AMG GT 63s

Ferrari F8 Tributo

And the program is the following:程序如下:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

public class GetOccurChar {
    static void GetOccurFile(File f) throws IOException {
        System.out.println("What letter do you want to check the occurence for in the file?");
        Scanner scan2 = new Scanner(System.in);
        char c = scan2.next().charAt(0);
        int count = 0;
        String str= "";
        char[] ch = new char[100];

        try {
            Scanner scan = new Scanner (f);
            
            while (scan.hasNextLine()) {
                str = scan.nextLine().toLowerCase();
                for (int i = 0; i < str.length(); i++)
                    ch[i] = str.charAt(i);
            }
            scan.close();
            for (int i = 0; i < ch.length; i++)
                if (ch[i] == c)
                    count++;
            System.out.println(c +" occures " + count + " times in the file.");
            System.out.println(ch);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

OUTPUT:输出:

What letter do you want to check the occurence for in the file?
t
t occures 2 times in the file.
ferrari f8 tributo 63so

Your while -loop tries to copy each line into your ch -array, overwriting any previous lines in the process.您的while循环尝试将每一行复制到您的ch数组中,覆盖该过程中的任何先前行。 After the loop only the last line and any remainders from previous lines not yet overwritten remain.在循环之后,仅保留最后一行和尚未覆盖的前几行的任何剩余部分。 Only then you perform your search, basically only searching the last line.只有这样你才能执行搜索,基本上只搜索最后一行。 In order to search all lines you will have to do your search while iterating over the lines, eg by putting the second loop inside the first loop:为了搜索所有行,您必须在迭代行时进行搜索,例如将第二个循环放在第一个循环中:

while (scan.hasNextLine()) {
    str = scan.nextLine().toLowerCase();
    for (int i = 0; i < str.length(); i++)
        ch[i] = str.charAt(i);
    for (int i = 0; i < ch.length; i++)
        if (ch[i] == c)
            count++;
}

Note that your array ch is a very very dangerous thing, if any line happens to have more than 100 characters your program will crash.请注意,您的数组ch是一件非常危险的事情,如果任何一行碰巧超过 100 个字符,您的程序就会崩溃。 In your current program it is not needed, you could check for your letter directly without storing the lines:在您当前的程序中不需要它,您可以直接检查您的信件而不存储行:

while (scan.hasNextLine()) {
    str = scan.nextLine().toLowerCase();
    for (int i = 0; i < str.length(); i++)
        if (str.charAt(i) == c)
            count++;
}

You do not need to create char[] ch = new char[100] .您不需要创建char[] ch = new char[100] All you need to do is to compare each character of the string with the desired character and increase count whenever a match is found.您需要做的就是将字符串的每个字符与所需的字符进行比较,并在找到匹配项时增加count Also, make sure to convert the input to lower case before getting the desired character (the first character) from it because you are converting each line of the file into the lower case before iterating its characters.此外,请确保在从中获取所需字符(第一个字符)之前将输入转换为小写,因为您在迭代其字符之前将文件的每一行都转换为小写。

static void GetOccurFile(File f) throws IOException {
    System.out.println("What letter do you want to check the occurence for in the file?");
    Scanner scan2 = new Scanner(System.in);
    char c = scan2.next().toLowerCase().charAt(0); // Lower case
    int count = 0;
    String str = "";
    try {
        Scanner scan = new Scanner(f);
        while (scan.hasNextLine()) {
            str = scan.nextLine().toLowerCase();
            for (int i = 0; i < str.length(); i++) {
                if (c == str.charAt(i)) { // Compare
                    count++;
                }
            }
        }
        scan.close();
        System.out.println(c + " occurs " + count + " times in the file.");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM