分享

Java学习——100、判断回文字符串

 pythonjava学习 2021-04-06

回文字符串:即字符串“从前向后读”和“从后向前读”都相同。

算法并不难,用循环,将字符串的第0个和最后一个比较,第1个和倒数第二个比较,到中间数字为止,都相等则为回文字符串,反之,则不是。

其完整代码如下:

package la;

import java.awt.*;

import javax.swing.*;

import javax.swing.event.*;

import java.awt.event.*;

public class Huiwen extends JFrame implements ActionListener{

 private JTextField text;

 private JButton button;

 public Huiwen() {

  super("回文判断");

  this.setVisible(true);

  this.setSize(300,100);

  this.setLocationRelativeTo(null);

  JPanel top=new JPanel();

  this.getContentPane().add(top,"North");

  top.add(new JLabel("请输入字符串:"));

  text=new JTextField(10);

  top.add(text);

  button=new JButton("是否回文?");

  this.getContentPane().add(button);

  button.addActionListener(this);

}

@Override

public void actionPerformed(ActionEvent arg0) {

// TODO 自动生成的方法存根

  String s=text.getText();

  if(s=="") {

    new Panduan("您未输入任何数据");

    this.dispose();

  }

  else {

    String s1="";

    int i,j;

    for(i=0,j=s.length()-1;i<s.length()/2;i++,j--) {

        if(s.charAt(i)==s.charAt(j))

        continue;

    else {

        s1=s+"不是回文";

        break;

    }

  }

  if(i==j||i==s.length()/2)

  s1=s+"是回文";

  new Panduan(s1);

  this.dispose();

  }

 }

}

class Panduan extends JFrame implements ActionListener{

  private JButton b1,b2;

  private JLabel l;

  public Panduan(String s) {

  super("判断");

  this.setVisible(true);

  this.setSize(200,100);

  this.setLocationRelativeTo(null);

  this.setLayout(new FlowLayout());

  this.getContentPane().add(new JLabel(s));

  b1=new JButton("确定");

  b1.addActionListener(this);

  this.getContentPane().add(b1);

}

@Override

public void actionPerformed(ActionEvent arg0) {

// TODO 自动生成的方法存根

  this.dispose();

  new Huiwen();

 }

public static void main(String args[]) {

  new Huiwen();

 }

}

其运行结果为:

输入字符串后:

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多