繁体   English   中英

在Java中,如何通过检测某个单词来设置要执行的操作?

[英]In java, how can I set an action to happen by detecting a certain word?

因此,对于我的代码,我有一个基本的“聊天机器人”和类,该类可以生成非常基本的面孔(面孔可以微笑或皱眉或无聊),最后我有一个驱动程序类。

我的问题是:当我检测到某个单词(用词组)时,是否有可能使我的代码产生微笑/皱眉/无聊的行为

这是我到目前为止的内容:

ChatBot类:

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;

import java.awt.Color;

import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

import java.lang.Math;


public class ChatBot extends JFrame implements KeyListener{
JPanel p = new JPanel();
JTextArea dialog = new JTextArea(20,50);
JTextArea input = new JTextArea(1,50);
JScrollPane scroll = new JScrollPane(
    dialog,
    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
);

String[][] chatBot={
    //standard greetings
    {"hi","hello","hola","ola","howdy" , "wassup", "sup", "bonjour", },
    {"hi","hello","hey"},
    //question greetings
    {"how are you","how r you","how r u","how are u, how are you?, how are you ?", "wassup"},
    {"good","doing well", "not bad", "meh", "I could be better", "However you want me to be "},
    //yes
    {"yes"},
    {"no"},
    //default
    {"how was your day?"}
};

public static void main(String[] args){
    new ChatBot();
}

public ChatBot(Changingface x){
    super("Chat Bot");
    setSize(600,400);
    setResizable(false);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    dialog.setEditable(false);
    input.addKeyListener(this);

    p.add(scroll);
    p.add(input);
    p.setBackground(new Color(75,14,215));
    add(p);

    setVisible(true);

    x= new ChangingFace();//need help with this, teacher told me to make a parameter for the constructor and then make code that 
                         //was able to detect a word in a phrase and respond accordingly to that word/phrase

    if(input.getText("day")){//this is how far I got

      }


}

public void keyPressed(KeyEvent e){
    if(e.getKeyCode()==KeyEvent.VK_ENTER){
        input.setEditable(false);
        //-----grab quote-----------
        String quote=input.getText();
        input.setText("");
        addText("-->You:\t"+quote);
        quote.trim();
        while(
            quote.charAt(quote.length()-1)=='!' ||
            quote.charAt(quote.length()-1)=='.' ||
            quote.charAt(quote.length()-1)=='?'// how are you? how are you ?
        ){
            quote=quote.substring(0,quote.length()-1);
            quote.trim();
        }
        byte response=0;
        /*
        0:we're searching through chatBot[][] for matches
        1:we didn't find anything
        2:we did find something
        */
        //-----check for matches----
        int j=0;//which group we're checking
        while(response==0){
            if(inArray(quote.toLowerCase(),chatBot[j*2])){
                response=2;
                int r=(int)Math.floor(Math.random()*chatBot[(j*2)+1].length);
                addText("\n-->Chatty McChatface:\t"+chatBot[(j*2)+1][r]);
            }
            j++;
            if(j*2==chatBot.length-1 && response==0){
                response=1;
            }
        }

        //-----default--------------
        if(response==1){
            int r=(int)Math.floor(Math.random()*chatBot[chatBot.length-1].length);
            addText("\n-->Chatty McChatface:\t"+chatBot[chatBot.length-1][r]);
        }
        addText("\n");
    }
}

public void keyReleased(KeyEvent e){
    if(e.getKeyCode()==KeyEvent.VK_ENTER){
        input.setEditable(true);
    }
}

public void keyTyped(KeyEvent e){}

public void addText(String str){
    dialog.setText(dialog.getText()+str);
}

public boolean inArray(String in,String[] str){
    boolean match=false;
    for(int i=0;i<str.length;i++){
        if(str[i].equals(in)){
            match=true;
        }
    }
    return match;
}

}

之后,我有我的脸部课程:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ChangingFace extends JFrame implements ActionListener
{
 int whichFeel = 0;
 private JButton happyButton = new JButton("Cheeky Smirk");
 private JButton thinkButton = new JButton("Bored");
 private JButton sadButton = new JButton("Somethin fishy");

 public ChangingFace()
 {
    // set the title
    setTitle("Face behind the ChatBot");

 // choose a Flow Layout policy
 setLayout(new FlowLayout());

 // add the buttons to the frame
 add(happyButton);
 add(thinkButton);
 add(sadButton);

 // set the background to cyan
 getContentPane().setBackground(Color.cyan);

 // enable the buttons to listen for a mouse-click
 happyButton.addActionListener(this);
 thinkButton.addActionListener(this);
 sadButton.addActionListener(this);

 // configure the frame
 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 setSize(720, 420);//250,200
 setLocation(100,100);//300,300
 setVisible(true);
}

 public void paint(Graphics g)
  {
   // call the paint method of the superclass, Jframe
   super.paint(g);
   // paint the face
   g.setColor(Color.red);//red yellow blue orange pink cyan magenta black white gray lightGray darkGray
                      //http://mathbits.com/MathBits/Java/Graphics/Color.htm
  g.drawOval(85,75,75,75);//85,75,75,75
  g.setColor(Color.darkGray);
  g.fillOval(100,95,10,10);//100,95,10,10
  g.fillOval(135,95,10,10);//135,95,10,10
  g.drawString("Savage OGB lgt", 79,181);
  g.drawRect(121, 150, 3, 20);//121,150,3,20
  if(whichFeel == 1)
   {
    // draw a smiling mouth
    g.drawArc(102,115,40,25,0,-180);
   }
   else if(whichFeel == 3)
  {
    // draw a frowning mouth
    g.drawArc(102,115,40,25,0,180);
  }
   else if(whichFeel == 2)
  {
    // draw a thinking mouth
    g.drawLine(102, 130, 142, 130);
  }
}
  public void actionPerformed(ActionEvent e)
 {
 if(e.getSource() == happyButton)
 {
 whichFeel = 1;
 repaint();
 }
 if(e.getSource() == thinkButton)
 {
 whichFeel = 2;
 repaint();
 }
 if(e.getSource() == sadButton)
 {
 whichFeel = 3;
 repaint();
  }
 }
}

和驱动程序类:

public class ChangingFaceTester{
 public static void main(String[] args){
  new ChangingFace();
  new ChatBot();
 }
}

再次提出我的问题:如何通过检测用户输入中的短语/单词来使自己的脸微笑/皱眉/思考(无聊)?

您可以使用String.contains()方法。

if(input.getText().contains("beer"){
    x.setWhichFeel(1); // x is the variable name you gave your ChangingFace
}                      // instance in the chatbot class

编辑:

public class ChangingFace(){

    private int whichFeel;

    public void setWhichFeel(int num){
       whichFeel = num;
    }
}

可以从ChatBot类中调用此方法,以更改ChangeFace类中的whichFeel变量。

编辑2:

您的ChatBot构造函数需要一个参数,ChangeingFace对象:

public ChatBot(Changingface x){
}

在您的主要方法中,您有:

public static void main(String[] args){
    new ChatBox();
}

由于ChatBot需要一个参数,因此您应该传递一个ChangeingFace对象。

public static void main(String[] args){
    new ChatBox(new ChangingFace());
}

您还提到驱动程序类具有main方法。 应该只有一种主要方法。 它在哪个类中都没有关系,但是请记住,您的chatBox对象必须接受ChangesFace对象作为参数。

编辑3:

进一步检查后,将main方法保留在ChangesFaceTester类中,但将其结构如下:

public class ChangingFaceTester{
    public static void main(String[] args){
        new ChatBot(new ChangingFace());
    }
}

暂无
暂无

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

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