我正在努力完成以下任务:
任务q: 使用字符串类中的方法,编写一个程序,该程序将计算字符串中由空格分隔的单词数。为简单起见,请使用没有标点符号的字符串或其他空格字符(制表符,换行符等)。使用JTextArea允许用户输入文本并允许文本区域在必要时滚动。当用户点击按钮对单词进行计数时,计算的单词总数将显示在用户无法修改的文本框中。
现在我的问题是我没有在不可编辑的文本框中显示计数的数字。 我也有问题,其中cusrsor显示在输入屏幕的中间而不是顶部。
请你指出我正确的方向。
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.util.*;
public class WordCounter extends JFrame implements ActionListener
{
//Construct a panel for the fields and buttons
JPanel fieldPanel = new JPanel();
JPanel buttonPanel = new JPanel();
//Construct labels and text boxes
JTextField screen = new JTextField(1);
JLabel wordCount = new JLabel(" Word Count = ");
JTextField words = new JTextField(3);
//Construct button
JButton countButton = new JButton("Count Words");
public static void main(String[] args)
{
WordCounter f = new WordCounter();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500,200);
f.setTitle("Word Counter");
f.setResizable(false);
f.setLocation(200,200);
f.setVisible(true);
}
public static int getWordCount(String screen)
{
int count = 0;
for (int i = 0; i < screen.length(); i++)
{
if (screen.charAt(i) == ' ')
{
count++;
}
}
return count;
}
public WordCounter()
{
Container c = getContentPane();
c.setLayout((new BorderLayout()));
fieldPanel.setLayout(new GridLayout(1,1));
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
//add rows to panels
fieldPanel.add(screen);
//add button to panel
buttonPanel.add(countButton);
buttonPanel.add(wordCount);
buttonPanel.add(words);
//add panels to frame
c.add(fieldPanel, BorderLayout.CENTER);
c.add(buttonPanel, BorderLayout.SOUTH);
//add functionality to button
countButton.addActionListener(this);
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
int answer = JOptionPane.showConfirmDialog(null,"Are you sure you want to exit?", "File Submission",JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION)
System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent e)
{
}
}
答案 0 :(得分:0)
要显示字数,您必须修改actionPerformed
方法,如下所示:
public void actionPerformed(ActionEvent e)
{
words.setText(String.valueOf(getWordCount(screen.getText())));
}
如果输入的文本没有以空格结尾,那么计算单词的方法也会产生错误的结果。您可以像这样修改getWordCount
方法以获得正确的字数:
public static int getWordCount(String screen)
{
String[] words = screen.split("\\s+");
return words.length;
}
对于您的第二个问题:您的光标显示在中心,因为JTextField
是单行输入。请改用JTextArea
。毕竟在你的问题中指明你应该使用它:
JTextArea screen = new JTextArea();
答案 1 :(得分:0)
试一试:
public static int getWordCount(String screen) { int count = 0;
string[] words = screen.split(' ');
count = words.Length;
return count;
}