java - 如何搜索多个单词然后计算它们。只为一个单词编写代码

标签 java

我有我编写的代码,但该程序有问题。

这个程序是一个带有我创建的界面的字计数器。 它计算我在 test.txt 中写入单词“Vlad Enache”*(我的名字)的次数。问题是我不知道如何让它搜索多个单词,比如说 Vlad Enache,以及单词“狗”和“猫”。我想知道如何从另一个带有字段的框架中的用户输入中定义这些单词。

谢谢:)

import java.awt.Color;
import java.awt.EventQueue;
import java.io.*;
import java.util.Scanner;

import javax.swing.JFrame;
import javax.swing.JTextField;

import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;

import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
import javax.swing.JTextArea;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;


public class Andreea {

private JFrame frame;
private JTextField textField;
private JButton btnNewButton;
private JLabel lblNewLabel;
private JTextArea txtrVlad;
private JMenuBar menuBar_2;
private JMenu menu;
private JMenuItem menuItem;


/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Andreea window = new Andreea();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
/**
 * Read from file
 * @throws IOException 
 */
public int ReadFromFile() throws IOException{       

    BufferedReader br;
    Scanner ob;
    br = new BufferedReader(new FileReader("D:/test.txt"));      
    ob = new Scanner("PULA");
    String str=ob.next();
     String str1="",str2="";
     int count=0;
     while((str1=br.readLine())!=null)
     {
     str2 +=str1;



    }  

     int index = str2.indexOf(str);

     while (index != -1) {
     count++;
     str2 = str2.substring(index + 1);
     index = str2.indexOf(str);
    }
     return count;
}


/**
 * Create the application.
 * @throws IOException 
 */
public Andreea() throws IOException {
    initialize();
}

/**
 * Initialize the contents of the frame.
 * @throws IOException 
 */
private void initialize() throws IOException {
    frame = new JFrame();
    frame.getContentPane().setBackground(new Color(255, 255, 255));
    frame.setBounds(100, 100, 497, 399);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    textField = new JTextField();
    textField.setBackground(new Color(255, 255, 255));
    textField.setForeground(new Color(0, 204, 204));
    textField.setHorizontalAlignment(SwingConstants.CENTER);
    textField.setEditable(false);
    textField.setFont(new Font("Georgia", Font.BOLD | Font.ITALIC, 20));
    textField.setBounds(129, 190, 223, 45);
    frame.getContentPane().add(textField);
    textField.setColumns(10);





    JButton btnCount = new JButton("Count");
    btnCount.setFont(new Font("Verdana", Font.BOLD | Font.ITALIC, 10));
    btnCount.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            int count=0;
            try {
                count = ReadFromFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

            String str="";
            str += count;
            textField.setText(str + " Times" );

        }
    });
    btnCount.setBounds(60, 270, 130, 45);
    frame.getContentPane().add(btnCount);

    btnNewButton = new JButton("Reseteaza Counter");
    btnNewButton.setFont(new Font("Verdana", Font.BOLD | Font.ITALIC, 10));
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            textField.setText(null);
        }
    });
    btnNewButton.setBounds(293, 267, 130, 45);
    frame.getContentPane().add(btnNewButton);

    lblNewLabel = new JLabel("New label");
    lblNewLabel.setIcon(new ImageIcon("C:/...."));
    lblNewLabel.setBounds(0, 0, 480, 179);
    frame.getContentPane().add(lblNewLabel);

    txtrVlad = new JTextArea();
    txtrVlad.setText("\u00A9 2014 Vlad Enache (4594)");
    txtrVlad.setBounds(310, 338, 204, 22);
    frame.getContentPane().add(txtrVlad);

    menuBar_2 = new JMenuBar();
    frame.setJMenuBar(menuBar_2);

    menu = new JMenu("New menu");
    menuBar_2.add(menu);

    menuItem = new JMenuItem("New menu item");
    menuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        }
    });
    menu.add(menuItem);

}

}

最佳答案

这是一种可能的解决方案。请注意,此代码假定每行一个标记。如果不是这样,您可以返回到 String.indexOf

public int[] ReadFromFile(final String[] tokens) throws IOException
{

    final int[] counters = new int[tokens.length];
    BufferedReader br;
    br = new BufferedReader(new FileReader("D:/test.txt"));
    String str1 = "";

    while ((str1 = br.readLine()) != null)
    {
        for (int i = 0; i < tokens.length; i++)
            if (str1.contains(tokens[i]))//if the line contains the token
                counters[i]++;// increase counter for the index of the token

    }

    return counters;
}

...


public void actionPerformed(ActionEvent arg0)
{
    //final String[] tokens = new String[] { "Vlad Enache", "dog", "cat" };
    final String[] tokens = textField.getText().split(", ");//get token directly from JTextfield.
   // Would make more sense to use a different JtextField for input and output. 
   //This is just an example
    try
    {
        int[] count;
        count = ReadFromFile(tokens);

        final StringBuilder sb = new StringBuilder();//storing the result in a stringbuilder

        /* to display the utterance of each token 
        for (int i = 0; i < count.length; i++)
            sb.append(tokens[i] + " is repeated " + count[i] + " times\n");

        textField.setText(sb.toString());//displaying result
        */

        //to sum up all count value
        int sum = 0;
        for(int c : count)
           sum+=c;
        textField.setText(sum+" times");



    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

}

关于java - 如何搜索多个单词然后计算它们。只为一个单词编写代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26590308/

相关文章:

java - 创建 pi(x) 表

java - 用于单击除具有特定名称的链接之外的所有链接的 WebDriver 脚本不起作用

java - Hibernate 搜索前缀

java - eclipse 不接受在 eclipse.ini 中设置堆大小

java - wsimport 结果具有不同的运行时端点

java - 带有自定义适配器的抽屉导航 react 不正确

java - 我可以在setcontentview android之前以编程方式创建ImageView吗

java - 在哪里设置 Apache Kafka 中的最大消息大小?

java - Java 中更好的 Html 生成器

java - Spark-sample() 函数复制数据?