键盘输入一行字符串。将字符按字典序顺序输出,统计每个字符出现的次数和出现位置,统计含有单词个数,正向和反向输出单词

2021/5/5 10:55:32

本文主要是介绍键盘输入一行字符串。将字符按字典序顺序输出,统计每个字符出现的次数和出现位置,统计含有单词个数,正向和反向输出单词,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

package start;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeMap;

public class sevevpointnineteo extends JFrame{
private JLabel a1;
private JTextField inputField;
private JTextArea outputArea;
private JButton b1,b2;
public sevevpointnineteo(){
super("分析语句");
super.setBackground(Color.black);
Container container=getContentPane();
container.setLayout(new FlowLayout());
a1=new JLabel("请输入一个句子;");
container.add(a1);
inputField=new JTextField(25);
container.add(inputField);
b1=new JButton("按题意输出结果");
container.add(b1);
outputArea=new JTextArea(10,25);
outputArea.setEditable(false);
container.add(new JScrollPane(outputArea));
b2=new JButton("退出");
container.add(b2);
ActionEventHandler handler=new ActionEventHandler();
b1.addActionListener(handler);
b2.addActionListener(handler);
setSize(300,400);
setVisible(true);
}
private class ActionEventHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
if(event.getSource()==b2)
System.exit(0);
else if(event.getSource()==b1){
String str=inputField.getText();
char charArry[]=new char[str.length()];
str.getChars(0, str.length(), charArry, 0);
TreeMap<Character,Integer>tm=new TreeMap<Character,Integer>();
for(char ch:charArry){
Integer i=tm.get(ch);
if(i==null)
tm.put(ch, 1);
else{
++i;
tm.put(ch, i);
}
}
Set<Character>set=tm.keySet();
outputArea.setText("字符"+'\t'+"出现次数"+'\t'+"出现位置"+"\n");
for(Character key:set){
StringBuilder sb = new StringBuilder();
for(int i=0;i<charArry.length;i++){
if(charArry[i]==key)
sb.append(i+1).append(" ");
}
Integer value=tm.get(key);
StringBuilder op=new StringBuilder();
op.append(key).append('\t').append(value).append('\t').append(sb.toString());
outputArea.append(op+"\n");
}
Arrays.sort(charArry);
outputArea.append("按字典序输出:");
for(int i=0;i<charArry.length;i++)
outputArea.append(Character.toString(charArry[i]));
outputArea.append("\n");
String[]tokens=str.split(" ");
outputArea.append("单词个数:"+tokens.length+"\n");
outputArea.append("正向输出单词:"+"\n");
for(String element:tokens)
outputArea.append(element+"\n");
outputArea.append("反向输出:"+"\n");
for(int i=tokens.length-1;i>=0;i--)
outputArea.append(tokens[i]+"\n");
}
}
}
public static void main(String args[]){
sevevpointnineteo test=new sevevpointnineteo();
}
}



这篇关于键盘输入一行字符串。将字符按字典序顺序输出,统计每个字符出现的次数和出现位置,统计含有单词个数,正向和反向输出单词的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程