Java编程

用java跟图灵机器人对话

很多人都玩过微信,其中就有与机器人聊天的功能:

这个图灵机器人网站提供了相关的API接口,可以在程序中利用,过程如下:

2.在Java程序中接入机器人:

3.一个简单的聊天程序:

import java.awt.FlowLayout;import java.awt.Font;import java.awt.GridLayout;import java.awt.Image;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.beans.EventHandler;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JColorChooser;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextArea;import javax.swing.JTextField;public class 图灵机器人 {public 图灵机器人() {}public static void main(String[] args) throws IOException {String information = new String(“Hello”);String mechine = new String();JFrame frame = new JFrame(“与机器人聊天”);JPanel panel = new JPanel(new GridLayout(3,1));JPanel questionPanel = new JPanel(new FlowLayout());JPanel buttonPanel = new JPanel();JPanel answerPanel = new JPanel(new FlowLayout());JLabel question = new JLabel(“问题”);JTextField enterQuestion = new JTextField(20);JLabel answer = new JLabel(“机器人回答”);JTextArea enterAnswer = new JTextArea(3,25);JButton submit = new JButton(“提交”);// ImageIcon imgIcon = new ImageIcon(“images/robot.png”);// Icon img = imgIcon;// JLabel imgLabel = new JLabel();frame.setSize(600, 400);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);enterAnswer.setFont(new Font(“宋体”,Font.BOLD,15));enterQuestion.setFont(new Font(“宋体”,Font.BOLD,15));// imgIcon.setImage(imgIcon.getImage().getScaledInstance(35,35,Image.SCALE_DEFAULT));enterAnswer.setLineWrap(true);// imgLabel.setIcon(img);questionPanel.add(question);questionPanel.add(enterQuestion);// answerPanel.add(imgLabel);answerPanel.add(answer);answerPanel.add(enterAnswer);buttonPanel.add(submit);panel.add(questionPanel);panel.add(answerPanel);panel.add(buttonPanel);frame.add(panel);submit.addActionListener(new ActionListener(){@Overridepublic void actionPerformed(ActionEvent e) {String answer = new String();String q = enterQuestion.getText();try {answer = machine(q);} catch (IOException e1) {e1.printStackTrace();}enterAnswer.setText(answer);}});enterQuestion.addKeyListener(new KeyListener() {@Overridepublic void keyTyped(KeyEvent e) {// TODO Auto-generated method stub}@Overridepublic void keyPressed(KeyEvent e) {if(e.getKeyCode()==10

e.getKeyCode()==38) {String answer = new String();String q = enterQuestion.getText();try {answer = machine(q);} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}enterAnswer.setText(answer);}}@Overridepublic void keyReleased(KeyEvent e) {// TODO Auto-generated method stub

Similar Posts

发表评论

邮箱地址不会被公开。 必填项已用*标注