簡體   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